Client validation for textbox
Purpose:
* When you click the submit button, the client validation should be done inside the textbox.
* If okey go to actionresult.
If not, display a pop-up message with instruction "max 10 letter" with an OK button.
The criteria are a maximum of 10 letters.
Problem:
I don't know how to do this.
Info:
* I am using VS2013 with ASP.net mvc, jQuery, javascript
* No server validation.
<!DOCTYPE html>
<html>
<body>
<form>
First name: <input type="text" name="FirstName" value="Mickey"><br>
<input type="submit" value="Submit">
</form>
</body>
</html>
<form id="target">
First name: <input type="text" name="FirstName" id="txtname" ><br>
<input type="submit" value="Submit">
</form>
and Js
$( "#target" ).submit(function( event ) {
var getText=$('#txtname').val().trim();
var len=getText.length;
if(len > 10){
alert('max 10 size');
event.preventDefault();
}
});
check the length of the form submit.
DEMO
To perform such checks, you must use data annotations with razor syntax. There is no need to write separate code. Take a look at the following example
public class TestClass
{
[DisplayName("Description")]
[StringLength(100, MinimumLength = 10)]
[Required]
public string Description { get; set; }
[DisplayName("Supply Type")]
[Required]
public int SupplyType { get; set; }
[DisplayName("Activation Date")]
[Required]
[DataType(DataType.DateTime)]
public DateTime ActivationDate { get; set; }
}
In the view write the following
@using (Html.BeginForm("Create", "CO2Config", FormMethod.Post)
{
@Html.AntiForgeryToken()
@Html.ValidationSummary(true)
//your code
}
Use the code below.
<!DOCTYPE html>
<html>
<head>
<script>
function form_validate(){
var name= document.getElementById("name");
if(name=="")
{
alert("Name is required !!");
return false;
}
if(name.length>10)
{
alert("Name is not more than 10 character !!");
return false;
}
return true;
}
<script>
</head>
<body>
<form onsubmit="return form_validate();">
First name: <input id="name" type="text" name="FirstName" value=""><br>
<input type="submit" value="Submit">
</form>
</body>
</html>
No need for separate javascript code, in class definition using data annotation, define what validation needs to be done and to just bind the control to this model. The @ Html.ValidationSummary (true) syntax will ensure that the validations are performed.
Please refer to the following link. This will clarify how to use data annotations http://www.codeproject.com/Tips/160184/Basic-Data-Validation-Using-Data-Annotations-ASP-N