Why Javascript validation is not working in html form? - javascript

When i try name box is fill with character it always show that "Name must be in character only.".
Here is Javascript code:
function validate_form() {
if (!(/^[A-Za-z]+$/).test(document.emp.new_name.value)) {
alert("Name must be in character only.");
return false;
}
if (!(/^\d{10}$/).test(document.emp.new_number.value)) {
alert("Enter valid mobile number");
return false;
}
if (!(/^[0-9.]+$/).test(document.emp.new_salary.value)) {
alert("salary must be numeric");
return false;
}
if (!(/^\w+([\.-]?\w+)*#\w+([\.-]?\w+)*(\.\w{2,3})+$/).test(document.emp.new_email.value)) {
alert("You have entered an invalid email address!")
return (false);
}
alert ("success");
return true;
}

Because initially it does not have any characters, try adding a check to character length
Checkout example
$("#submit").on("click",function(){
var name = $("#name").val();
if (name.length>0 && !(/^[A-Za-z]+$/).test(name)) {
alert("Name must be in character only.");
return false;
}
else{
alert("ok");
}
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input id="name"><input type="submit" id="submit">

var name = document.emp.new_name.value;
if (name.value.search(/[^a-zA-Z]+/) === -1) {
alert("Name must be in character only.");
return false;
}
Try with this code. Hopefully, this will work.

Related

JavaScript Irish Mobile Regex

I'm trying to validate a form to check among other things that a user has added a valid Irish mobile which should start with 083,085,086,087,089 and be ten digits in length
I looked at Validate an Irish mobile phone number but I can't get it to work
My check function
function CheckPhone(pNumb) {
var paswd=/08[3679]-\d{0,10}$/;
return paswd.test(pNumb);}
Where I try to validate
if(!CheckPhone(d))
{
alert("You have not entered a valid Irish mobile number");
document.getElementById('phoneNumber').focus();
return false;
}
But even with a valid number I'm told that the entry is invalid. I'm sure I've done something wrong but I'm new to regex and not a programmer so not sure what.
In response to Jayce444 I've edited my question to include the full script as when I add the checkphone function it causes the email and password functions to be ignored and the form is submitted with invalid values present for these fields such as test#test and p2 for the password
<script>
function validateEmail(email) {
var re = /^(([^<>()[\]\\.,;:\s#\"]+(\.[^<>()[\]\\.,;:\s#\"]+)*)|(\".+\"))#((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/;
return re.test(email);
}
function CheckPassword(inputtxt) {
var paswd=/^(?=.*\d)(?=.*[a-z])(?=.*[A-Z]).{8,20}$/;
return paswd.test(inputtxt);
}
function CheckPhone(pNumb) {
var paswd=08[3679]-\d{7}$;
return paswd.test(pNumb);
}
function validateForm() {
var a=document.forms["subForm"]["firstName"].value;
if (a===null || a==="")
{
alert("All fields in the form are required You must enter your first name");
document.getElementById('firstName').focus();
return false;
}
var b=document.forms["subForm"]["lastName"].value;
if (b===null || b==="")
{
alert("All fields in the form are required You must enter your last name");
document.getElementById('lastName').focus();
return false;
}
var c=document.forms["subForm"]["email"].value;
if (c===null || c==="")
{
alert("All fields in the form are required You must enter your email address");
document.getElementById('email').focus();
return false;
}
if(validateEmail(c)===false)
{
alert("You must enter a valid email address");
document.getElementById('email').focus();
return false;
}
var d=document.forms["subForm"]["phoneNumber"].value;
if (d===null || d==="")
{
alert("All fields in the form are required You must enter your phone number");
document.getElementById('phoneNumber').focus();
return false;
}
if(CheckPhone(d)===false)
{
alert("You have not entered a valid Irish mobile number");
document.getElementById('phoneNumber').focus();
return false;
}
var e=document.forms["subForm"]["password"].value;
if (e===null || e==="")
{
alert("All fields in the form are required You must enter a password");
document.getElementById('password').focus();
return false;
}
if(CheckPassword(e)===false)
{
alert("You have not entered a valid password");
document.getElementById('password').focus();
return false;
}
}
</script>
This regex works:
08[3679]-\d{7}$
Btw this site: https://regex101.com/ is good to help test regexes and see what they're actually doing. The second part of yours, \d{0,10} says "match 0 to 10 digits". What you want is to match exactly 7 digits after the dash.

Trying to create login form for username and password, something doesnt work int the form

Im trying to develop login form with username and password that have to be verified and match certain requirements. I am struggling with the form, not sure what i am missing,,,also login button doesny show up as button.
Any help appreciated.
<body>
<form onlogin="return checkForm(this);">
<p><input type="text" name="username" placeholder="Enter Username"></p>
<p><input type="password" name="pwd1" placeholder="Enter Password"></p>
<p><button type="login"placeholder="Login"></p>
<p> Forgot your password?</p>
</form>
<script type="text/javascript">
function checkForm(form)
{
if(form.username.value == "") {
alert("Error: Username cannot be blank!");
form.username.focus();
return false;
}
re = /^\w+$/;
if(!re.test(form.username.value)) {
alert("Error: Username must contain only letters, numbers and underscores!");
form.username.focus();
return false;
}
if(form.pwd1.value != "") {
if(form.pwd1.value.length < 6) {
alert("Error: Password must contain at least six characters!");
form.pwd1.focus();
return false;
}
if(form.pwd1.value == form.username.value) {
alert("Error: Password must be different from Username!");
form.pwd1.focus();
return false;
}
re = /[0-9]/;
if(!re.test(form.pwd1.value)) {
alert("Error: password must contain at least one number (0-9)!");
form.pwd1.focus();
return false;
}
re = /[a-z]/;
if(!re.test(form.pwd1.value)) {
alert("Error: password must contain at least one lowercase letter (a-z)!");
form.pwd1.focus();
return false;
}
re = /[A-Z]/;
if(!re.test(form.pwd1.value)) {
alert("Error: password must contain at least one uppercase letter (A-Z)!");
form.pwd1.focus();
return false;
}
} else {
alert("Error: Please check that you've entered and confirmed your password!");
form.pwd1.focus();
return false;
}
alert("You entered a valid password: " + form.pwd1.value);
return true;
}
`
The reason the button is not showing up is because there is no closing tag . Also don't forget to add text between the opening and closing tag.
<body>
<form id="form">
<p><input type="text" name="username" placeholder="Enter Username"></p>
<p><input type="password" name="pwd1" placeholder="Enter Password"></p>
<p><button type="login"placeholder="Login" onclick="myform()">Login</button></p>
<p>Forgot your password?</p>
</form>
Changed the html and added a onclick event to call a function.
function myform(){
var form = document.getElementById("form");
checkForm(form);
}
function checkForm(form)
{
if(form.username.value == "") {
alert("Error: Username cannot be blank!");
form.username.focus();
return false;
}
re = /^\w+$/;
if(!re.test(form.username.value)) {
alert("Error: Username must contain only letters, numbers and underscores!");
form.username.focus();
return false;
}
if(form.pwd1.value != "") {
if(form.pwd1.value.length < 6) {
alert("Error: Password must contain at least six characters!");
form.pwd1.focus();
return false;
}
if(form.pwd1.value == form.username.value) {
alert("Error: Password must be different from Username!");
form.pwd1.focus();
return false;
}
re = /[0-9]/;
if(!re.test(form.pwd1.value)) {
alert("Error: password must contain at least one number (0-9)!");
form.pwd1.focus();
return false;
}
re = /[a-z]/;
if(!re.test(form.pwd1.value)) {
alert("Error: password must contain at least one lowercase letter (a-z)!");
form.pwd1.focus();
return false;
}
re = /[A-Z]/;
if(!re.test(form.pwd1.value)) {
alert("Error: password must contain at least one uppercase letter (A-Z)!");
form.pwd1.focus();
return false;
}
} else {
alert("Error: Please check that you've entered and confirmed your password!");
form.pwd1.focus();
return false;
}
alert("You entered a valid password: " + form.pwd1.value);
return true;
}
</body>
See working version here

JS Numeric and Hyphen validation

I am using Javascript to validate phone number with hyphen. It is validating only one hyphen but not allowing two hyphens.
I want to validate this format:
123-456-7891
How can I do this with JS?
This is my function
function numericValidation(phoneno) {
var numbers = /^\d+((;\d+)*|-\d+)?$/;
if (phoneno.match(numbers)) {
alert('Your input is valid');
return true;
} else {
alert('Please enter in (123-456-7891) format');
return false;
}
}
function numericValidation(phoneno) {
var numbers =/^\d+(-\d+)*$/;
if (phoneno.match(numbers)) {
alert('Your input is valid');
return true;
}
else {
alert('Please enter in (123-456-7891) format');
return false;
}
}

Javascript code not working

The following code is not working. Want to check white spaces in an input field. If there are not any white spaces want to alert. Any help
<script language="javascript">
document.register.eventdtls.value;
function hasWhiteSpace(strg) {
var whiteSpaceExp=/\s+$/;
if (whiteSpaceExp.test(strg))
alert("Please Check Your Fields For Spaces");
return false;
else
return true;
}
</script>
You are missing brackets:
if (whiteSpaceExp.test(strg)) {
alert("Please Check Your Fields For Spaces");
return false;
} else {
return true;
}
Your current regex will only test for spaces at the end of the string (that's what the $ represents here);
Your regex should be:
var whiteSpaceExp=/\s+/;
Also, you need to put brackets around your if(){ } else{ } because you have multiple statements.
function hasWhiteSpace(strg) {
var whiteSpaceExp = /\s+/;
if (whiteSpaceExp.test(strg)) {
alert("Please Check Your Fields For Spaces");
return false;
}
else {
return true;
}
}
Kindly Use braces in your 'if' statement
if (whiteSpaceExp.test(strg))
{
alert("Please Check Your Fields For Spaces");
return false;
}
else
return true;

JavaScript validation for multiple functions?

I have a JavaScript function for a form. The code is :
<script type="text/javascript">
function verify() {
if (isNaN(document.form1.exp_amount.value) == true) {
alert("Invalid Block Amount");
return false;
} else if ((document.form1.exp_name.value).length == 0) {
alert("Block Exp is left Blank!");
return false;
} else if ((document.form1.exp_amount.value).length == 0) {
alert("Block Amount is left Blank!");
return false;
} else {
document.form1.submit();
return true;
}
}
</script>
Now I have to provide Alphabet Validation for it, which I have it in a separate JS function:
<script language="javascript" >
function checkName() {
re = /^[A-Za-z]+$/;
if (re.test(document.exp_name.form1.value)) {
alert('Valid Name.');
} else {
alert('Invalid Name.');
}
}
</script>
If I want to have Alphabet validation inside function verify(), how could I do it? Are there any other ways?
Please change your validation and form to this which will allow submission of the form if valid and not if errors. The following code is in my opinion canonical and will work on all browsers that support regular expressions (which was introduced in JS1.1 in 1996 with NS3.0) - please note that javascript does not support dashes in names unless you quote the field name in the script. The code does not need the form to be named since it passes the form object in the call (this) and uses the object in the function as theForm
<html>
<head>
<title>Canonical forms validation without jQuery</title>
<script type="text/javascript">
var validName = /^[A-Za-z]+$/;
function checkName(str) {
return validName.test(str);
}
function verify(theForm) {
// note: theForm["..."] is short for theForm.elements["..."];
var amount = theForm["exp_amount"].value;
if(amount ==""){
alert("Block Amount is left blank");
theForm["exp_amount"].focus();
return false;
}
if (isNaN(amount)) {
alert("Invalid Block Amount");
theForm["exp_amount"].focus();
return false;
}
var name = theForm["exp_name"].value;
if(name.length==0) {
alert("Block Exp is left Blank!");
theForm["exp_name"].focus();
return false;
}
if(!checkName(name)) {
alert("Block Exp is invalid!");
theForm["exp_name"].focus();
return false;
}
return true;
}
</script>
</head>
<body>
<form onsubmit="return verify(this)">
Amount: <input type="text" name="exp_amount" value="" /><br />
Name: <input type="text" name="exp_name" value="" /><br />
<input type="submit" />
</form>
</body>
</html>
Simply return false or true inside your checkName function:
function checkName()
{
re = /^[A-Za-z]+$/;
if(re.test(document.exp_name.form1.value))
{
alert('Valid Name.');
return true;
}
else
{
alert('Invalid Name.');
false;
}
}
Then call it and check the result.
...
else if((document.form1.exp_amount.value).length==0)
{
alert("Block Amount is left Blank!");
return false;
}
else if (!checkName()) {
return false;
}
else
{
document.form1.submit();
return true;
}
As an aside, there are many ways your code can be cleaned up and improved. I don't want to get into them now, but if you'd like to discuss it, just leave a comment.
Edit your checkName() function to
function checkName()
{
re = /^[A-Za-z]+$/;
if(re.test(document.exp_name.form1.value))
{
alert('Valid Name.');
return true;
}
else
{
alert('Invalid Name.');
return false;
}
}
And add
else if(!checkName()){ return false;}
to your validation code just before the form submit
<script type="text/javascript">
function verify()
{
if(isNaN(document.form1.exp_amount.value)==true)
{
alert("Invalid Block Amount");
return false;
}
else if((document.form1.exp_name.value).length==0)
{
alert("Block Exp is left Blank!");
return false;
}
else if((document.form1.exp_amount.value).length==0)
{
alert("Block Amount is left Blank!");
return false;
}
else if(!(/^[A-Za-z]+$/.test(document.form1.exp_amount.value))) //ADD THIS
{
alert('Invalid Name');
return false;
}
document.form1.submit();
return true;
}
</script>

Categories

Resources