Javascript code not working - javascript

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;

Related

Why Javascript validation is not working in html form?

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.

Unable to validate properly in jquery

I'm validating an input from a user in jquery. If the input is empty, false is returned and jquery code doesn't run and if it contains some text the jquery code runs.
Here is an example-
function sendm() {
var valid;
valid = sendmval();
if (valid) {
//jquery code
}
}
function sendmval() {
var valid = true;
if (!$('#message').val()) {
valid = false;
} else {}
return valid;
}
This works fine. However the problem occurs when user inputs blank spaces only and thus results in running of jquery code even on blank input. How can I prevent this ?
Since spaces count as character so you have to use $.trim() of Jquery like below:-
if (!$.trim($('#message').val())) {
valid = false;
}
For more reference:-
https://api.jquery.com/jQuery.trim/
Since space is also a character, simple use .trim() function of Javascript strings to remove blank space in the beginning and end. Then proceed with your check as usual.
Note: I have changed:
if (!$('#message').val())
to
if (!$('#message').val().trim())
See full working code test:
function sendm() {
var valid;
valid = sendmval();
if (valid) {
alert("valid & sendm");
}
}
function sendmval() {
var valid = true;
if (!$('#message').val().trim()) {
valid = false;
} else {}
return valid;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" id="message">
<button onclick="sendm()">CHECK</button>

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;
}
}

check whether a textarea is empty

Can anyone please tell me what the problem is with this code:
function c(id)
{
var empty = document.getElementById(id);
if(empty.length<1)
{
window.alert ("This field cant be left empty");
return true;
}
else
{
return false;
}
}
This is my html code:
<textarea rows="3" cols="80" id="ta1" onChange="c('ta1');"></textarea>
The value property of the textarea should be checked to determine if it is empty.
var content = document.getElementById(id).value;
if(content.length<1)
{
window.alert ("This field cant be left empty");
return true;
}
else
{
return false;
}
Working Example: http://jsfiddle.net/35DFR/2/
Try this:
function c(id)
{
if(document.getElementById(id).value == '')
{
window.alert ("This field cant be left empty");
return true;
}
else
{
return false;
}
}
If you want to go a bit further, you might want to trim the value first though.
Update:
From the comments, try changing the 'onchange' to 'onkeyup':
<textarea rows="3" cols="80" id="ta1" onkeyup="c('ta1');"></textarea>
if (YOURFORM.YOURTEXTFIELDVARIABLENAME.value == "")
{
return True
}
function c(id) {
var empty =document.getElementById(id);
if(!empty.value){
window.alert("This field cant be left empty");
return true;
}else{
return false;
}
}
try this

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