How to set mobile number validation on my jsp page? - javascript

i am using this script for validation can anybody help me where i am wrong. i am using this foe mobile number validation.when i run this code with jquery it is not working.
function mobilenumber() {
if(document.getElementById('mobnum').value != ""){
var y = document.getElementById('mobnum').value;
if(isNaN(y)||y.indexOf(" ")!=-1)
{
alert("Invalid Mobile No.");
document.getElementById('mobnum').focus();
return false;
}
if (y.length>10 || y.length<10)
{
alert("Mobile No. should be 10 digit");
document.getElementById('mobnum').focus();
return false;
}
if (!(y.charAt(0)=="9" || y.charAt(0)=="8" || y.charAt(0)=="7"))
{
alert("Mobile No. should start with 9 ,8 or 7 ");
document.getElementById('mobnum').focus();
return false
}
}
}
<input type="submit" value="INSERT"class="btn"onclick="submitForm();">
jquery is
$(document).ready(function(){
function submitForm(){
if(mobilenumber()){
$('#form1').submit(function(){
});
}
else{
alert("Please Input Correct Mobile Numbers");
}
}
});

Use HTML5 Pattern
<input type="number" pattern=".{10}" title="Enter Valid Mob No" required>

var mobile = document.getElementById("mobnum").value;
var numericmob = isNumber(mobile );
if(!numericmob)
{
alert("Enter only positive numbers into the Contact Number field.");
return false;
}
if(mobile.length!=10)
{
alert("Enter 10 digits Contact Number.");
return false;
}
// write function that checks element is number or not
function isNumber(elem)
{
var re = /^[0-9]+$/;
str = elem.toString();
if (!str.match(re))
{
return false;
}
return true;
}
Advantage of this function is you can use it for checking any numeric field on your form, such as id, amount etc.

Use jQUery .submit() function to submit the form after validation is true
<form id="myForm" action="abc.php" method="post">
<!-- Your Form -->
<button onclick="submitForm();">Submit</button>
</form>
now to check if form data is valid here
function submitForm(){
if(mobilenumber()){
$('#myForm').submit();
}
else{
alert("Please Input Correct Mobile Numbers");
}
}
EDIT:
Use the #Aniket's isNumber function to check length and digit in mobile number field. Which is more generic.

if(document.getElementById('mobile_number').value != ""){
var y = document.getElementById('mobile_number').value;
if(isNaN(y)||y.indexOf(" ")!=-1)
{
alert("Invalid Mobile No.");
document.getElementById('mobile_number').focus();
return false;
}
if (y.length>10 || y.length<10)
{
alert("Mobile No. should be 10 digit");
document.getElementById('mobile_number').focus();
return false;
}
if (!(y.charAt(0)=="9" || y.charAt(0)=="8" || y.charAt(0)=="7"))
{
alert("Mobile No. should start with 9 ,8 or 7 ");
document.getElementById('mobile_number').focus();
return false
}
}
try this... this will be needful for you... and if you are looking for ragex pattern then use this....
^([0|\+[0-9]{1,5})?([7-9][0-9]{9})$

Related

I want to make a registration form but the script wont work the way i want

To validate the checkpoint the form will have to show an alert if
One of the inputs is empty
The password has less than 8 characters
Doesn't have a valid e-mail adress
The password must be a combination of charatacters , numbers and at least a capital letter
And finally the reset button will reset all the inputs to empty :
//Variable declaration
var username=document.forms["Registration"]["name"];
var e_mail=document.forms["Registration"]["email"];
var password=document.forms["Registration"]["psw1"];
var passwordcheck=document.forms["Registration"]["psw2"];
//add eventListener
username.addEventListener("blur", NameVerify, true);
e_mail.addEventListener("blur", EmailVerify, true);
password.addEventListener("blur", PasswordVerify, true);
passwordcheck.addEventListener("blur", PasswordVerify, true);
// validate the registration
function Validate(){
if (username.value=="")
{
alert("username is required");
username.focus()
return false;
}
if (e_mail.value=="")
{
alert("Email is required");
e_mail.focus()
return false;
}
if (password.value=="")
{
alert("Password is required");
password.focus()
return false;
}
if (passwordcheck.value=="")
{
alert("Re-enter your password");
passwordcheck.focus()
return false;
}
if(password.value != passwordcheck.value){
alert("Password do not match!!")
passwordcheck.focus()
return false;
}
}
//check the username value
function NameVerify(username){
if (username.value !=0) {
document.querySelector.backgroundColor = lightGrey;
return true;
}
}
//check the e_mail
function EmailVerify(e_mail){
if (/^\w+([\.-]?\w+)*#\w+([\.-]?\w+)*(\.`\w{2,3})+$/.test(Registration.email.value))`
{
return (true)
}
alert("You have entered an invalid email address!")
e_mail.focus()
return (false)
}
//check the password
function PasswordVerify(password){
var psw = /^(?=.*\d)(?=.*[a-z])(?=.*[A-Z])(?=.*[^a-zA-Z0-9])(?!.*\s).{8,20}$/;
if(password.value.match(psw))
{
alert('Correct, try another...')
return true;
}
else
{
alert('Wrong!!')
return false;
}
}
// clear all text inputs when the page is loaded
function clearInp() {
document.getElementsByTagName("input").value = "";
return true;
}
//reset all text fields
function Reset() {
document.querySelector("#Registration").reset();
return true;
}
None of this requires any JavaScript at all.
One of the inputs is empty
<input type="text" required />
The password has less than 8 characters
<input type="password" minlength="8" />
Doesn't have a valid e-mail adress
<input type="email" />
The password must be a combination of charatacters , numbers and at least a capital letter
<input type="password" pattern="(?=.*[a-z])(?=.*[A-Z])(?=.*[0-9]).{8,}" />
And finally the reset button will reset all the inputs to empty
<input type="reset" value="Reset form" />
Once you've eliminated all JavaScript code from your form, you will find that your form no longer has any JavaScript errors ;)

How to check if textbox value is not number?

<!DOCTYPE html>
<html>
<body>
<div id="text" class="CommentBox">
Some text :
<input type="text" />
</div>
<script>
$(document).ready(function () {
jQuery("#text").on("change", function () {
var x = $('#text').value;
if (isNaN(x))
{
window.alert("You have entered not a number");
return false;
});
});
});
</script>
</body>
</html>
I am trying to write javascript code to check if the given value is not number.If not i would like to give error message? If it is number I would like to check if it is integer and between 0 and 100.
Basically you need to convert to an Int before compare it with NaN which means something like:
var x = $('#text').value;
if ( isNaN( parseInt(x) ) ) {
// Not a decimal number.
}
There are a lot of syntax errors in your code.
Your selector checks your div for the change event instead of your input, which means it will never trigger the code.
You should use .val() to get the value of an element when using jQuery selectors instead of .value.
You can also use the this keyword inside the event handler to get the referenced element.
Besides that there were some misplaced ) and } in your code.
Below I have included an working sample of your code.
$(document).ready(function() {
jQuery("#text > input").on("change", function() {
var x = $(this).val();
if (isNaN(x)) {
window.alert("You have entered not a number");
return false;
} else if (x > 0 && x < 100) {
alert("number in between 0 and 100");
}
})
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="text" class="CommentBox">
Some text :
<input type="text" />
</div>
function numberOrNot(var input)
{
try
{
Integer.parseInt(input);
}
catch(NumberFormatException ex)
{
return false;
}
return true;
}
this will return true if your input is number, otherwise it will return false
try this code
you enter direct input on change or write id for input and pass it to javascript
$(document).ready(function() {
jQuery("input").on("change", function() {
var x = $('#text').val();
if (isNaN(x)) {
window.alert("You have entered not a number");
return false;
}
else{
if(x>=0 && x<=100)
{
window.alert("You have enter write number");
}else{
window.alert("You enter number between 0 to 100");
}
}
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="CommentBox">
Some text :
<input type="text" id="text" />
</div>
You can use try-catch and put as many conditions you want in try block Like this. I have put three conditions for now.
<script type="text/javascript">
function Validation(){
var number1=document.LoginForm.number1.value;
try{
if(number1==""){
throw "Empty";
}
if(isNaN(number1)){
throw "Not a Number";
}
if(number1<0 || number1>100){
throw "Out of range";
}
}
catch(err){
if (err=="Empty"){
alert("Number 1 and Number 2 fields cannot be empty");
}
if (err=="Not a Number"){
alert("Please enter a number");
}
if(err=="Out of Range"){
alert("Out of Range");
}
return false;
}
//return true;
}
</script>

Javascript Email validation that allows a null value

I have this on submit function that checks for the email field to have a properly formatted address. Works fine. However, I want the field to allow a null value as this particular input is optional and not required. I know this should be simple, Im missing the obvious. Someone point me in the right direction...
EDIT: Providing the entire form validation this time. As every time I just replace the email portion its breaking other pieces....
function validateSMSForm()
{
if (SMSForm.PID_Form.value.length < 4)
{
alert("Please enter a valid Partner ID");
return false;
}
if (SMSForm.area.value.length < 3)
{
alert("Please enter a valid 10-digit cell phone number");
return false;
}
if (SMSForm.prefix.value.length < 3)
{
alert("Please enter a valid 10-digit cell phone number");
return false;
}
if (SMSForm.line.value.length < 4)
{
alert("Please enter a valid 10-digit cell phone number");
return false;
}
<!-- EMAIL VALIDATION HERE
if (/^\w+([\.-]?\w+)*#\w+([\.-]?\w+)*(\.\w{2,3})+$/.test(form.emailaddress.value))
{
return (true)
}
alert("Please enter a valid email address")
return (false)
-->
}
Add a check for empty/null string first:
if ((!form.emailaddress.value) || (/^\w+([.-]?\w+)#\w+([.-]?\w+)(.\w{2,3})+$/.test(form.emailaddress.value))) {
//handle valid e-mail
} else {
//handle invalid e-mail
}
Like this
Assuming
<form onsubmit="return validateSMSForm(this)">
JavaScript:
function isEmail(str) {
return !str || /^\w+([\.-]?\w+)*#\w+([\.-]?\w+)*(\.\w{2,})+$/.test(str);
}
function validateSMSForm(SMSForm) {
if (SMSForm.PID_Form.value.length < 4) {
alert("Please enter a valid Partner ID");
return false;
}
if (SMSForm.area.value.length < 3 ||
SMSForm.prefix.value.length < 3 ||
SMSForm.line.value.length < 4) {
alert("Please enter a valid 10-digit cell phone number");
return false;
}
if (!isEmail(SMSForm.emailaddress.value)) {
alert("Please enter a valid email address")
return false; //
}
return true; // allow submission
}
var email = form.emailaddress.value;
if (!email){ return true } // this what your looking for?
if (/^\w+([.-]?\w+)#\w+([.-]?\w+)(.\w{2,3})+$/.test(email))
{
return (true)
}
alert("Please enter a valid email address")
return (false)

Validating Password

I'm trying to validate a password using javascript, It's to make sure that when changing the password, the new password entered is equal to that of the re-entering of the new password (user is asked to enter their new password twice so both have to match) but at the same time, i want to make sure that the new password is at least 6 characters long, I have these functions separately but don't know how to combine them... thanks for help in advance!
This is what i have so far...
This is to make sure the new passwords match:
function validatePassword()
{
var new_password = document.getElementById("new_password").value;
var confirm_new_password = document.getElementById("confirm_new_password").value;
<!-- if they match, go to next page -->
if ( new_password == confirm_new_password)
{
return true;
}
<!-- if they don't match, an error message is displayed -->
else
{
alert("Passwords do not match.");
}
return false;
}
This is for length of password:
function validatePassword()
{
if (document.getElementById("new_password").value.length < "5")
{
<!--If pasword is less than 5 characters long, display error message-->
alert("Please ensure your password is at least 6 characters long.");
return false;
}
return true;
}
How do i combine both of these to form a SINGLE function where the two new passwords are checked so that they match, and also check that they are longer than 6 characters?
To just combine your two functions, this would work:
function validatePassword()
{
var new_password = document.getElementById("new_password").value;
var confirm_new_password = document.getElementById("confirm_new_password").value;
if (new_password.length < 5)
{
<!--If pasword is less than 5 characters long, display error message-->
alert("Please ensure your password is at least 6 characters long.");
return false;
}
else if ( new_password != confirm_new_password)
{
alert("Passwords do not match.");
return false;
}
else
{
return true;
}
}
Although I agree, there are better procedures out there. And please, make sure you're doing server-side validation as well since client-side validation is very easy to skip around.
i m not sure but you can call validatePassword() this function inside
if ( new_password == confirm_new_password)
{
validatePassword();
}
You have two options, either make the two functions a single function, or make them two separate functions and call them both before you submit / process your form.
if (validatePasswordLength() && validatePasswordsMatch()) {
// Continue
}
you have to try this code that is small and working.
if(document.getElementById("new_password").value != document.getElementById("confirm_new_password").value){
alert("Passwords do not match.");
return false;
}
<script>
function validatePassword()
{
var new_password = document.getElementById("new_password").value;
var confirm_new_password = document.getElementById("confirm_new_password").value;
if (document.getElementById("new_password").value.length < "5")
{
alert("Please ensure your password is at least 6 characters long.");
return false;
}
if (new_password == confirm_new_password)
{
alert("Password no match");
return false;
}
return true;
}
</script>
<form action="" onsubmit="return validatePassword()">
<p>New Password: <input type="password" id="new_password" name="new_password" /></p>
<p>Confirm Password: <input type="password" id="confirm_new_password" name="confirm_new_password" /></p>
<p><input type="submit" value="submit" /></p>
</form>

Form Validation

JS:
validate document.forms();
if (document.forms[0].userAge.value == "") {
alert("Age field cannot be empty.");
return false;
}
if (document.forms[0].userAge.value < 5) {
alert("Your age input is not correct.");
return false;
}
if (userage == isNumber) {
alert("Your age input is not correct.");
return false;
}
alert("Name and Age are valid.");
return true;
HTML:
<label for="userAge">Age:</label>
<input type="text" name="userAge" id="userAge" />
</div>
If this is the code I have, how would I make it so that if someone were to enter a non number in the age text box an alert would come up saying " Your input is not correct"?
Edit: I originally suggested using parseInt with isNaN() to test if the input was non-numeric. Well, it seems that using a regex is preferrable not only formatching cases like "4a" correctly, but it's actually faster in many cases (surprise!).
I mocked up some HTML with a button to illustrate.
HTML:
<form>
<label for="userAge">Age:</label>
<input type="text" name="userAge" id="userAge" />
<input type="button" id="test" name="test" value="Test" />
</form>
JavaScript:
function validateForm() {
// get the input value once and use a variable
// this makes the rest of the code more readable
// and has a small performance benefit in retrieving
// the input value once
var userAge = document.forms[0].userAge.value;
// is it blank?
if (userAge === "") {
alert("Age field cannot be empty.")
return false;
}
// is it a valid number? testing for positive integers
if (!userAge.match(/^\d+$/)) {
alert("Your age input is not correct.")
return false;
}
// you could also test parseInt(userAge, 10) < 5
if (userAge < 5) {
alert("Your age input is not correct.")
return false;
}
alert("Name and Age are valid.");
return true;
}
// trigger validateForm() however you want, I did this as an example
document.getElementById("test").onclick = validateForm;
​Here is a jsFiddle to demonstrate: http://jsfiddle.net/willslab/m2spX/6/
About the regex: userAge.match(/^\d+$/) returns true if userAge only contains a positive integer. The beginning / and ending / indicate a regular expression literal. \d indicates ASCII digits only. + matches one or more occurrences of the previous pattern (digits in this case). ^ indicates match from the beginning, and $ indicates match until the end. So /^\d+$/ is a regex literal matching only ASCII digits from beginning to end!
Also note that you can combine the last two if statements using an OR operator (||). I left these isolated in case you want to give each one a unique validation message.
It would look like this:
if (!userAge.match(/^\d+$/) || userAge < 5) {
alert("Your age input is not correct.")
return false;
}
Feel free to ask any questions about the code and I will explain. I hope that helps!
I recommend you to use the following Javascript which will not allow non-numeric characters in the text field.
function isNumberKey(evt)
{
var charCode = (evt.which) ? evt.which : event.keyCode;
if (charCode > 31 && (charCode < 48 || charCode > 57))
{
return false;
}
return true;
}
<input type="text" id="userAge" name="userAge" onkeypress="return isNumberKey(event);">
Try this solution
<script language="javascript">
function validate(){
alert("validate ..."+document.forms[0].userAge.value);
if (document.forms[0].userAge.value == ""){
alert("Age field cannot be empty.");
return false;
}
if (document.forms[0].userAge.value<5){
alert("Your age input is not correct.");
return false;
}
//provide a way to validate if its numeric number..maybe using regexp
//if (isNumeric(userAge)){
// alert("Your age input is not correct.");
// return false;
//}
//alert"Name and Age are valid."
return true;
}
</script>
The HTML should be
<form>
<div><label for="userAge">Age:</label>
<input type="text" name="userAge" id="userAge" onblur="validate()"/>
</div>
</form>
use the code below
if(isNaN(document.forms[0].userAge.value)){
alert('This is not a number');
}

Categories