I am trying to display a customized message when the text entered does not match the pattern.
Following is the code I have used.
<input pattern="[a-zA-Z0-9]" name="firstName" id="firstname" required="" type="text" />
When I enter a valid text like 'akshay'; it is showing me the invalid message:
'Please match the requested format'
Also, I want to change this message to a customized one. I tried using the code given above but its is not working. Below is the code I have used below:
<script>
document.getElementById("firstname").addEventListener("invalid", function (e) {
var elem = e.target;
if (elem.value != "") {
e.target.setCustomValidity('Cannot contain special characters');
}
});
</script>
Please help me with this code.
Try to use oninvalid method in the input tag
<input pattern="[a-zA-Z0-9]*" name="firstName" id="firstname" required="required"
type="text" oninvalid="oninvalid="this.setCustomValidity(this.willValidate?'':'Cannot contain special characters')" />
Related
So I have the required error message showing the input + id that is attached to it in the html
<div class="form-validation">
<input class="modal-input" id="password" type="password" placeholder="Enter your
password">
<p>Error Message</p>
</div>
<div class="form-validation">
<input class="modal-input" id="password-confirm" type="password" placeholder="Confirm your password">
<p>Error Message</p>
</div>
So as you can see, the id's equal password and then password-confirm
Now the problem is I don't know how to create a custom text to change it from saying password-confirm to just saying password without overlapping with the id names.
Here's a picture below of what I mean
And here is the function that I wrote in order to get the "Password-confirm" to display
function getFieldName(input) {
return input.id.charAt(0).toUpperCase() + input.id.slice(1);
}
And here is my function the make sure the required fields show the error message with the getFieldName as the first word in the message
function checkRequired(inputArr) {
inputArr.forEach(function (input) {
if(input.value.trim() === '') {
showError(input, `${getFieldName(input)} is required`);
} else {
showValid(input);
}
});
}
I tried to just target the type on the input instead of the id, but I run into another issue because the input type="text" displays "Text is required" when I want it to say "Username" so I need a method to be able to create any custom word + "is required"
So essentially I could customize it to say "WHATEVER is required"
add a data tag to the html elements you are targeting. and use it do display whatever you require to display.
refer to How to store arbitrary data for some HTML tags for details.
I guess I'm doing a trivial error somewhere but will be grateful if someone can spot it.
I am trying to validate a postcode in a form field once it has been typed in. Similar code works fine in PHP but I've spent hours and the JS does not seem to be executing whatever I do.
Here is part of the form (all within body tags):
<form name ="register" method="post" action="<?php echo htmlspecialchars($_SERVER['PHP_SELF']); ?>" autocomplete="off">
...
<script type="text/javascript" src="common.js">
</script>
<input type="text" name="postcode" class="form-control" placeholder="Postcode" maxlength="10" value='' onchange="isValidPostcode(this.form)" required />
Here are versions of the javascript (stuffed with alerts just to print out something).
Version 1:
function isValidPostcode(form) {
alert("called");
var p = document.register.postcode.value;
var postcodeRegEx = '/^([g][i][r][0][a][a])$|^((([a-pr-uwyz]{1}([0]|[1-9]\d?))|([a-pr-uwyz]{1}[a-hk-y]{1}([0]|[1-9]\d?))|([a-pr-uwyz]{1}[1-9][a-hjkps-uw]{1})|([a-pr-uwyz]{1}[a-hk-y]{1}[1-9][a-z]{1}))(\d[abd-hjlnp-uw-z]{2})?)$/i';
if (postcodeRegEx.test(p)) alert("OK");
else alert("This does not look a valid UK postcode...");
}
Version 2 (is called without a parameter):
function isValidPostcode() {
alert("called");
var p = document.getElementById('postcode').value.replace(/\s/g,'');
var postcodeRegEx = '/^([g][i][r][0][a][a])$|^((([a-pr-uwyz]{1}([0]|[1-9]\d?))|([a-pr-uwyz]{1}[a-hk-y]{1}([0]|[1-9]\d?))|([a-pr-uwyz]{1}[1-9][a-hjkps-uw]{1})|([a-pr-uwyz]{1}[a-hk-y]{1}[1-9][a-z]{1}))(\d[abd-hjlnp-uw-z]{2})?)$/i';
if (postcodeRegEx.test(p)) alert("OK");
else alert("This does not look a valid UK postcode...");
}
I tried binding to other events but can't get a single alert out. Even exact reproduction of the examples is not working. Hope someone gives me an idea of what is wrong.
you should replace onchange with keyup and remove quotes from regex :)
<input type="text" name="postcode" class="form-control" placeholder="Postcode" maxlength="10" value='' onkeyup="isValidPostcode(this.value)" required />
function isValidPostcode(value) {
var postcodeRegEx = /^([g][i][r][0][a][a])$|^((([a-pr-uwyz]{1}([0]|[1-9]\d?))|([a-pr-uwyz]{1}[a-hk-y]{1}([0]|[1-9]\d?))|([a-pr-uwyz]{1}[1-9][a-hjkps-uw]{1})|([a-pr-uwyz]{1}[a-hk-y]{1}[1-9][a-z]{1}))(\d[abd-hjlnp-uw-z]{2})?)$/i;
if (postcodeRegEx.test(value)) console.log("OK");
else console.log("This does not look a valid UK postcode...");
}
You should use the keyup event to do that and add the event using JS, not inline it.
postcodeRegEx is a regex, not a string, you need to remove quotes around it.
function isValidPostcode() {
var p = document.getElementById('postcode').value.replace(/\s/g, '');
var postcodeRegEx = /^([g][i][r][0][a][a])$|^((([a-pr-uwyz]{1}([0]|[1-9]\d?))|([a-pr-uwyz]{1}[a-hk-y]{1}([0]|[1-9]\d?))|([a-pr-uwyz]{1}[1-9][a-hjkps-uw]{1})|([a-pr-uwyz]{1}[a-hk-y]{1}[1-9][a-z]{1}))(\d[abd-hjlnp-uw-z]{2})?)$/i;
if (postcodeRegEx.test(p)) alert("OK");
else alert("This does not look a valid UK postcode...");
}
document.getElementById("postcode").addEventListener("keyup", function() {
isValidPostcode();
});
<form name="register" method="post" action="" autocomplete="off">
<input id="postcode" type="text" name="postcode" class="form-control" placeholder="Postcode" maxlength="10" value='' required />
</form>
Here i have written some that is for validation on form in html and javascript
<!DOCTYPE html>
<html>
<body>
<form name="registration">
<input style="font-size:16px;" type="text" name="Name" placeholder="Full Name" onchange="checkName()" required />
</form>
<script>
function checkName()
{
var uname=document.registration.Name.value;
var letters = /^[A-Za-z]+$/;
if(uname.value.match(letters))
{
alert('fg');
}
else
{
alert('Username must have alphabet characters only');
//uname.focus();
}
}
</script>
</body>
</html>
Please describe why it is not working?
The problem is that you're trying to get the value property TWICE. Like such:
var uname=document.registration.Name.value;
if(uname.value.match(letters))
Your uname variable already contains the value, so you don't need to get it again. Change your if statement to this...
if (uname.match(letters))
And it works just fine :)
Using onchange with input type = "text" is quite uncommon
onchange event usually occurs only after you leave (blur) the control.
onchange is mainly associated with change of select element.
For your case it is better to use keydown, keyup and keypress events as well.
HTML
<input style="font-size:16px;" type="text" name="Name" placeholder="Full Name" onkeyup="checkName()" required />
Jsfiddle
I am using a subscribe news letter script by using MySQL and PHP. When the user enters the e-mail and clicks the button the e-mail is added to database.
The issue is that while clicking the button without entering an e-mail, the data base is updating with an empty record. How can I stop submitting the empty fields and force the user to enter an e-mail?
Here is my HTML:
<form id="myForm" action="update.php" method="post">
<input type="hidden" name="action" value="update" />
<input type="text" name="email" id="email" value="Enter your email here" onfocus="if (this.value == 'Enter your email here') {this.value = '';}" onblur="if (this.value == '') {this.value = 'Enter your email here';}" onwebkitspeechchange="this.value = this.value.replace('Enter your email here','')"; style=" color:#999; font-size:1em;width:200px; font-style:italic; font-family:"Times New Roman", Times, serif;"/>
<input class="button" type="image" src="rss.png" />
</form>
Sounds to me like you need to do some form validation before you take the user input and insert it into your database. It's dangerous to do as you're doing.
Why not use one of the many plugins out there:
http://www.queness.com/post/10104/powerful-javascript-form-validation-plugins
This is a useful tutorial on using the jquery validation plugin: http://docs.jquery.com/Plugins/Validation
Ignore the styling in their example and focus on the core aspects. In your case, the most useful line is:
<input id="cemail" name="email" size="25" class="required email" />
Roughly, you would need to do something like..
var form = $('#mtForm');
$('input').change(function(){
if($((this).val() == ''){
form.unbind('submit').submit(function(){
return false;
});
}
else{
form.unbind('submit');
}
})
You should change the value attribute of your email field to a placeholder attribute. The onfocus, onwebkitspeechchange and onblur code can be removed from the email input tag.
You can use something like this to check for a blank field if that's the only type of validation you're after (below is written with jQuery).
$(function(){
$('#myForm').submit(function(e){
if ($('#email').val().trim() == "") {
// some sort of notification here
e.preventDefault();
return false;
}
});
});
Ideally, you would validate the form on the client side (javascript/JQuery) as well as the server side (php).
For clarity I will remove the inline code on your input box to get this:
<input type="text" name="email" id="email" value="Enter your email here" />
Note - You may use
placeholder='Enter your email here'
to get the prompt in your input box.
Client side validation using HTML5
Make a required field with email format validation:
<input type="email" name="email" id="email" value="Enter your email here" required="required"/>
Client side validation using javascript/JQuery - example.js
JQuery:
$('#email').bind('blur', function() {
if (!validateEmail($(this).val()) {
// Add errors to form or other logic such as disable submit
}
});
function validateEmail($email) {
var emailReg = /^([\w-\.]+#([\w-]+\.)+[\w-]{2,4})?$/;
return emailReg.test($email);
}
}
Server side validation - update.php
// Require the email
if (empty($_POST['email'])) {
$error_message = 'You must enter an email!';
} else if (!filter_var($_POST['email'], FILTER_VALIDATE_EMAIL)) {
$error_message = 'Invalid email format. Example: example#example.example';
} else { // If no errors, continue processing the form
// process the form, enter email
}
The HTML5 alone will prevent submission of the form, however only more recent browsers support HTML5.
Hope this is helpful!
I have a form I cobbled together with bits of code copied online so my HTML and Javascript knowledge is VERY basic. The form has a button that will add another set of the same form fields when clicked. I added some code to make it so that if the "Quantity and Description" field is not filled out, the form won't submit but now it just keeps popping up the alert for when the field's not filled out even if it is. Here's is my script:
<script type='text/javascript' src='http://code.jquery.com/jquery-1.5.2.js'>
</script><script type='text/javascript'>
//<![CDATA[
$(function(){
$('#add').click(function() {
var p = $(this).closest('p');
$(p).before('<p> Quantity & Description:<br><textarea name="Quantity and Description" rows="10"
cols="60"><\/textarea><br>Fabric Source: <input type="text" name="Fabric Source"><br>Style# & Name: <input
type="text" name="Style# & Name"><br>Fabric Width: <input type="text" name="Fabric Width"><br>Repeat Information:
<input type="text" name="Repeat Info" size="60"><input type="hidden" name="COM Required" /> </p><br>');
return false;
});
});
function checkform()
{
var x=document.forms["comform"]["Quantity and Description"].value
if (x==null || x=="")
{
alert("Quantity & Description must be filled out, DO NOT just put an SO#!!");
return false;
}
}
//]]>
</script>
And here's my HTML:
<form action="MAILTO:ayeh#janusetcie.com" method="post" enctype="text/plain" id="comform" onSubmit="return
checkform()">
<div>Please complete this worksheet in full to avoid any delays.<br />
<br />Date: <input type="text" name="Date" /> Sales Rep: <input type="text" name="Sales Rep" /> Sales Quote/Order#: <input type="text" name="SQ/SO#" /><br />
<br />Quantity & Description: <font color="red"><i>Use "(#) Cushion Name" format.</i></font><br />
<textarea name="Quantity and Description" rows="10" cols="60">
</textarea>
<br />Fabric Source: <input type="text" name="Fabric Source" /><br />Style# & Name: <input type="text" name="Style# & Name" /><br />Fabric Width: <input type="text" name="Fabric Width" /><br />Repeat Information: <input type="text" name="Repeat Info" size="60" /><br /><font color="red"><i>Example: 13.75" Horizontal Repeat</i></font><br />
<br /><input type="hidden" name="COM Required" />
<p><button type="button" id="add">Add COM</button></p>
</div>
<input type="submit" value="Send" /></form>
How can I get it to submit but still check every occurence of the "Quantity and Description" field?
First, I would not use spaces in your input names, as then you have to deal with weird escaping issues. Use something like "QuantityAndDescription" instead.
Also, it looks like you're trying to have multiple fields with the same name. The best way to do that is to add brackets to the name, meaning the values will be grouped together as an array:
<textarea name="QuantityAndDescription[]"></textarea>
This also means the code has to get all the textareas, not just the first. We can use jQuery to grab the elements we want, to loop over them, and to check the values. Try this:
function checkform()
{
var success = true;
// Find the textareas inside id of "comform", store in jQuery object
var $textareas = $("form#comform textarea[name='QuantityAndDescription[]']");
// Loop through textareas and look for empty values
$textareas.each(function(n, element)
{
// Make a new jQuery object for the textarea we're looking at
var $textarea = $(element);
// Check value (an empty string will evaluate to false)
if( ! $textarea.val() )
{
success = false;
return false; // break out of the loop, one empty field is all we need
}
});
if(!success)
{
alert("Quantity & Description must be filled out, DO NOT just put an SO#!!");
return false;
}
// Explicitly return true, to make sure the form still submits
return true;
}
Also, a sidenote of pure aesthetics: You no longer need to use the CDATA comment hack. That's a holdover from the old XHTML days to prevent strict XML parsers from breaking. Unless you're using an XHTML Strict Doctype (and you shouldn't), you definitely don't need it.