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>
source to share
<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.
source to share
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
}
source to share
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>
source to share
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
source to share