Code for Validating Textbox with only characters and spaces in limited number [Resolved]

Posted by Rasagna under JavaScript on 12/29/2015 | Points: 10 | Views : 476 | Status : [Member] | Replies : 4
Hii,
I have a asp Textbox control where i have to validate it to accept only characters and spaces and not more than 20 characters and maximum of 2 spaces.If not satisfied display error message.I need JavaScript code to validate this.
Thanks in Advance..




Responses

Posted by: Rajeshatkiit on: 1/6/2016 [Member] Starter | Points: 50

Up
1
Down

Resolved
Hi

Please use this code for your need. It will help you.

var alphanumeric = "someStringHereghh hjhj j ";

var strLength = alphanumeric.split(" ").length - 1);

if (alphanumeric.length < 20)
{

alert('String should be more than 20 chars');

}

else if(strLength > 3)
{
alert('String should not contain more than 2 space');
}

else
{

var myRegEx = /^[A-Za-z ]+$/;
var isValid = myRegEx.test(alphanumeric);


}

Please mark it as answer if it helps you.

Rasagna, if this helps please login to Mark As Answer. | Alert Moderator

Posted by: Rajnilari2015 on: 1/7/2016 [Member] [Microsoft_MVP] [MVP] Platinum | Points: 50

Up
0
Down

Resolved
Try this

<html>

<head>
<script type="text/javascript">

function test(){

var originalString=document.getElementById('txtInput').value;
var myRegEx = /^[a-zA-Z]{0,20}(?:\s[a-zA-Z]{0,20}){0,2}$/;
var isValid = myRegEx.test(originalString);
alert(isValid);
}

</script>
</head>
<body>
<input type="button" id="btnValidate" value="Validate" onclick="test()"/>
<input type="text" id="txtInput" maxlength="20"/>
</body>
</html>


Hope that helps

--
Thanks & Regards,
RNA Team

Rasagna, if this helps please login to Mark As Answer. | Alert Moderator

Posted by: Jitendrasoft09 on: 12/31/2015 [Member] [MVP] Starter | Points: 25

Up
1
Down
Hi.

You can use regex to handle your validations as per given just sample code-
/^[A-Za-z ]+$/ or /^[A-Za-z\s]+$/


Refer below link-
http://stackoverflow.com/questions/7217766/regex-letters-only-validation-for-javascript-prompt

Jitendra Kumar
If my post helps you, plz mark as an answer.

Rasagna, if this helps please login to Mark As Answer. | Alert Moderator

Posted by: Professionaluser on: 12/31/2015 [Member] [MVP] Bronze | Points: 25

Up
-1
Down

Login to post response