Ok basically when I type , it won't allow it.
I want to add more like < > / \ etc how do I do it?
$("#in1").keypress(function (evt) {
if (String.fromCharCode(evt.which) == ",")
return false;
});
<input type="text" id="in1">
Can see the demo here. http://jsfiddle.net/QshDd/38/
If you have a list of disallowed characters, you can forbid them in this fashion:
$("#in1").keypress(function (evt) {
return [',', '<', '>', ].indexOf(String.fromCharCode(evt.which)) === -1;
});
its working , you Required to give more conditions:
$("#in1").keypress(function (evt) {
if (String.fromCharCode(evt.which) == ",")
return false;
if (String.fromCharCode(evt.which) == "<")
return false;
if (String.fromCharCode(evt.which) == ">")
return false;
if (String.fromCharCode(evt.which) == "\\")
return false;
});
Another Solution , either use regEx or use XMLParser or JSON parser methods.
if you want something like this
<input type="text"> ===> input typetext
$("#in1").keypress(function (evt) {
if (isValid(String.fromCharCode(evt.which)))
return false;
});
function isValid(str){
return /[~`!#$%\^&*+=\-\[\]\\';,/{}|\\":<>\?]/g.test(str);
}
http://jsfiddle.net/QshDd/61/
Try this, if you need only alphabets
$("#in1").keypress(function (evt) {
var expr = /^([a-zA-Z\s]+)$/i;
if (!String.fromCharCode(evt.which).match(expr))
return false;
});
var chars = new Array("<", ">" ,"/" ,"\\");
$("#in1").keypress(function (evt) {
if(!(chars.indexOf(String.fromCharCode(evt.which)) > -1))
return false;
});
Related
Okay, so I have a form. Applied a function to it.
All I want to do is when the form is submitted it launches the function, it checks to see if there is white space and throws out a message. I have the following:
function empty() {
var x;
x = document.getElementById("Username").value;
if (x == "") {
alert("Please ensure you fill in the form correctly.");
};
}
<input type='submit' value='Register' onClick='return empty()' />
<input type='text' id="Username" />
This is fine for if someone pressed the space-bar once and enters one line of whitespace, but how do I edit the function so that no matter how many spaces of whitespace are entered with the space-bar it will always throw back the alert.
Thanks in advance. I am very new to JavaScript. So please be gentle.
Trim the string before testing it.
x = document.getElementById("Username").value.trim();
This will remove any whitespace at the beginning and end of the value.
I have made a function for the same, i added another checks (including a regular expresion to detect multiples empty spaces). So here is the code:
function checkEmpty(field){
if (field == "" ||
field == null ||
field == "undefinied"){
return false;
}
else if(/^\s*$/.test(field)){
return false;
}
else{
return true;
}
}
Here is an example working with jquery: https://jsfiddle.net/p87qeL7f/
Here is the example in pure javascript: https://jsfiddle.net/g7oxmhon/
Note: the function checkEmpty still be the same for both
this work for me
$(document).ready(function() {
$('#Description').bind('input', function() {
var c = this.selectionStart,
r = /[^a-z0-9 .]/gi,
v = $(this).val();
if (r.test(v)) {
$(this).val(v.replace(r, ''));
c--;
}
this.setSelectionRange(c, c);
});
});
function checkEmpty(field) { //1Apr2022 new code
if (field == "" ||
field == null ||
field == "undefinied") {
return false;
} else if (/^\s*$/.test(field)) {
return false;
} else {
return true;
}
}
I am trying to validate a form using javascript. On button click function I have called a javascript function where I have displayed the message after the text box. The number of times I click the button same number of times message gets displayed just below the existing validation message. Please help me
Here goes my code:
function check() {
var v = true;
if ((document.getElementById('firstname').value == "")) {
$('#firstname').after('Validation message');
document.getElementById('firstname').style.borderColor='#DA394B';
v = false;
}
if ((document.getElementById('lastname').value == "")) {
$('#lastname').after('Some validation text');
document.getElementById('lastname').style.borderColor = '#DA394B';
v = false;
}
return v;
}
Assuming I understand what v is for. Which i probably don't because v (I hate one letter variable names...).
Try this:
function check() {
var v = true;
if ((document.getElementById('firstname').value == "")) {
if ($('#firstnameMessage').length <= 0)
{
$('#firstname').after('<p id="firstnameMessage">Validation message</p>');
document.getElementById('firstname').style.borderColor='#DA394B';
}
v = false;
}
if ((document.getElementById('lastname').value == "")) {
if ($('#lastnameMessage').length <= 0)
{
$('#lastname').after('<p id="lastnameMessage">Some validation text</p>');
document.getElementById('lastname').style.borderColor = '#DA394B';
}
v = false;
}
return v;
}
Simple fiddle to show this working: https://jsfiddle.net/srLt7wo0/
Using .after will insert another element per http://api.jquery.com/after/
The below solution uses a separate element already in the HTML to display the error message. If you use .after you have to check that you have not already added an element to your HTML
HTML
<input id="firstname" type="text"/><div id="firstnameMessage"></div>
<input id="lastname" type="text"/><div id="lastnameMessage"></div>
JS
function check() {
$("#firstnameMessage,#lastnameMessage").text(''); // clear message, reset border color
document.getElementById('firstname').style.borderColor='';
document.getElementById('lastname').style.borderColor='';
var isValid = true;
if ((document.getElementById('firstname').value == "")) {
$('#firstnameMessage').text('First name is required');
document.getElementById('firstname').style.borderColor='#DA394B';
isValid = false;
}
if ((document.getElementById('lastname').value == "")) {
$('#lastnameMessage').text('Last name is required');
document.getElementById('lastname').style.borderColor='#DA394B';
isValid = false;
}
return isValid;
}
I'm not sure to have understood you issue but maybe this could help you :)
window.firstname = document.getElementById('firstname')
window.lastname = document.getElementById('lastname')
window.issue = document.getElementById('issue')
function check() {
if(firstname.value == '' || lastname.value == '') {
issue.innerHTML = 'Please, use correct credentials.'
} else {
issue.innerHTML = ''
}
}
<input id="firstname" />
<input id="lastname" />
<button onclick="check()">
Check
</button>
<div id="issue" style="color:red;"></div>
This should work if i understand you.
It will add only one message no matter how many times you click
function check() {
var v = true;
if ((document.getElementById('firstname').value == "")) {
$('#message').remove()
$('#firstname').after('<span id='message'>Validation message</span>');
document.getElementById('firstname').style.borderColor='#DA394B';
v = false;
}
if ((document.getElementById('lastname').value == "")) {
$('#message').remove()
$('#lastname').after('<span id='message'>Some validation text</span>');
document.getElementById('lastname').style.borderColor = '#DA394B';
v = false;
}
return v;
}
I am trying to have my input only accept Numbers and the '.', it is working great but it doesn't allow for number pad number keys. I cant seem to find the exact answer online.
HTML
<input type="text" id="ItemTotal#i#" name="ItemTotal#i#" value="#qPriceAct#" onkeypress="return isNumeric(event)" onkeydown="return keyispressed(event);">
JavaScript
//prevent , and $ from being input
function keyispressed(e){
var charval= String.fromCharCode(e.keyCode);
if(isNaN(charval) && (e.which != 8 ) && (e.which != 190 )){
return false;
}
return true;
}
//is input numeric
function isNumeric (evt) {
var theEvent = evt || window.event;
var key = theEvent.keyCode || theEvent.which;
key = String.fromCharCode (key);
var regex = /[0-9]|\./;
if ( !regex.test(key) ) {
theEvent.returnValue = false;
if(theEvent.preventDefault) theEvent.preventDefault();
}
}
Thanks for the help!
The best way I believe would be to add a class to all the inputs that only allow numbers. Then you can restrict any input that doesn't match the pattern or a number/decimal.
function numberVerfication(value) {
var pattern=/^[0-9]*(\.)?[0-9]*$/;
if (value.match(pattern) != null){
return value
}
else {
var p=/[0-9]*(\.)?[0-9]*/;
return value.match(p)[0];
}
}
$('.numbersOnly').keyup(function(e) {
e.target.value = numberVerfication(e.target.value);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input class='numbersOnly' type="text" id="ItemTotal#i#" name="ItemTotal#i#" value="#qPriceAct#">
Simple using REGEXP
HTML
<input type="text" class='numbersOnly' id="ItemTotali" name="ItemTotal#i" value="qPriceAct">
JQUERY
$('.numbersOnly').keyup(function (e) {
this.value = this.value.replace(/[^0-9\.]/g, '');
});
JAVA SCRIPT
function numValidate(that){
that.value = that.value.replace(/[^0-9\.]/g, '');
}
<input type="text" onkeypress='numValidate(this)' onkeyup='numValidate(this)' class='numbersOnly' id="ItemTotali" name="ItemTotal#i" value="qPriceAct"/>
Demo
function numberVerfication(value){
return value.replace(/[^0-9.\-+]/g, '');
}
$('.numbersOnly').keyup(function(e){
e.target.value=numberVerfication(e.target.value);
});
What's wrong in it why it's not working...
<script language="JavaScript" type="text/javascript">
//function to check empty fields
function isEmpty(strfield1, strfield2) {
//change "field1, field2 and field3" to your field names
strfield1 = document.forms[0].name.value
strfield2 = document.forms[0].email.value
//name field
if (strfield1 == "" || strfield1 == null || !isNaN(strfield1) || strfield1.charAt(0) == ' ') {
alert( "Name is a mandatory field.\nPlease amend and retry.")
return false;
}
//EMAIL field
if (strfield2 == "" || strfield2 == null || !isNaN(strfield2) || strfield2.charAt(0) == ' ') {
alert(" Email is a mandatory field.\nPlease amend and retry.")
return false;
}
return true;
}
//function to check valid email address
function isValidEmail(strEmail){
validRegExp = /^[^#]+#[^#]+.[a-z]{2,}$/i;
strEmail = document.forms[0].email.value;
// search email text for regular exp matches
if (strEmail.search(validRegExp) == -1) {
alert('A valid e-mail address is required.\nPlease amend and retry');
return false;
}
return true;
}
//function that performs all functions, defined in the onsubmit event handler
function check(form)){
if (isEmpty(form.field1)){
if (isEmpty(form.field2)){
if (isValidEmail(form.email)){
return true;
}
}
}
}
return false;
}
</script>
It doesn't do anything I don't understand what's going there and in form I put this too
<form onsubmit="return check(this);" action="sendquery.php" name="contquery">
First glance: too many brackets as shown by #FishBasketGordo so I will not repeat
Second glance - you pass the field and do not test the field value
Third glance: You do not pass the correct names to the function
Fourth glance - isEmpty returns false when empty. It should return true
I fixed all those
DEMO HERE
Complete page to show where what goes. Updated to do unobtrusive event handling on the form
<html>
<head>
<title>Validation</title>
<script type="text/javascript">
// trim for IE
if(typeof String.prototype.trim !== 'function') {
String.prototype.trim = function() {
return this.replace(/^\s+|\s+$/g, '');
}
}
//function to check empty fields
function isEmpty(objfld) {
var val = objfld.value;
if (val.trim() == "" || val == null) {
alert(objfld.name+" is a mandatory field.\nPlease amend and retry.");
objfld.focus();
return true;
}
return false;
}
//function to check valid email address
function isValidEmail(objEmail){
var validRegExp = /^[^#]+#[^#]+.[a-z]{2,}$/i;
var strEmail = objEmail.value;
if (strEmail.match(validRegExp)) return true;
alert('A valid e-mail address is required.\nPlease amend and retry');
objEmail.focus();
return false;
}
//function that performs all functions, defined in the onsubmit event handler
function validate(form) {
if (isEmpty(form.name)) return false;
if (isEmpty(form.email)) return false;
return isValidEmail(form.email);
}
window.onload=function() {
document.getElementById("form1").onsubmit=function() {
return validate(this);
}
}
</head>
<body>
<form id="form1">
Name:<input type="text" name="name" /><br/>
Email:<input type="text" name="email" /><br/>
<input type="submit" />
</form>
</body>
</html>
Probably the main reason it isn't working is the syntax errors:
// Syntax error ----v
function check(form)){
if (isEmpty(form.field1)){
if (isEmpty(form.field2)){
if (isValidEmail(form.email)){
return true;
}
}
}
}
// The return statement should be above the previous closing bracket
// and the final closing bracket removed.
return false;
}
There's an extra closing paren on the first line, and there are too many closing brackets. If you open up this up in FireBug or Chrome Developer Tools or a similar tool, it would tell you about this automatically.
I wrote a javascript validation script to validate if the URL contains '+' or whitespaces.
$.validator.addMethod("reportFileURL",
function(value,element){
if(((value.search(/[+]+/)) == -1)
&& ((value.search(/[ ]+/))) == -1){
return true;
}
},"Invalid filename");
Can i write the script more precise than this.
if (value.search(/[\s+]/) == -1) {
return true;
}
return value.search(/[ +]/) == -1;