Html5 form element "required" on iPad/iPhone doesn't work - html

iPad safari is supposed to be html5 compliant, but it seems that the required element doesn't work. Anyone know why, or have a decent workaround that doesn't require a ton of JavaScript?
My code
<input type=email class=input placeholder="Email" name="email" required>

It's not supported in iOS yet: when can I use: required.

This is a jQuery solution to the issue, it highlights the input fields that have failed in a pinky colour too.
$('form').submit(function(){
var required = $('[required="true"]'); // change to [required] if not using true option as part of the attribute as it is not really needed.
var error = false;
for(var i = 0; i <= (required.length - 1);i++)
{
if(required[i].value == '') // tests that each required value does not equal blank, you could put in more stringent checks here if you wish.
{
required[i].style.backgroundColor = 'rgb(255,155,155)';
error = true; // if any inputs fail validation then the error variable will be set to true;
}
}
if(error) // if error is true;
{
return false; // stop the form from being submitted.
}
});

Since iOS 10.3 this atrributes are supported. Also e-mail type require writing the # symbol and so on...

If you are already using jQuery, Modernizr, and yepnope, this is one way to deal with it. If you aren't then this will add a lot of extra javascript.
My solution

I guess you can do something before the submit action like this
<form name="myForm" action="valid.html" onsubmit="checkValid()" method="post">
... ...
</form>
after pressing submit button, checkValid() is evoked before it actually submits. a return value of truewill continue the submit action.
refer to this post for further explanation.:)

If you use PHP, you can add a validation like this
function validation(){
if(isset($_POST['submit'])){
$email = $_POST['email'];
if(empty($email)){
echo $error = "Your email cannot be empty";
} else {
return true; //or do something next here
}
}
You then add this function in php before your form.

Related

Why does text input in form fields become disabled when I switch from a web browser to another window and then back again?

I have a web application that uses a lot of text input. In some cases it's form input and a Submit / POST action and in others the input text is processed using JavaScript / Ajax.
If I begin typing into, for example, a textarea and then switch to another window (e.g. Outlook) to copy some content to the clipboard, and then switch back to the browser to paste it, the textarea no longer accepts keyboard input.
This only appears to happen on my Windows 10 Pro laptop. On Mac OS it works fine.
I've used multiple browsers.
Is there something in the Windows setup that disables form input as a security measure?
Here is an example of a form declaration in the markup:
<form method="post" action="<?php echo __SITE_URL; ?>admin/_editcandidate.php" autocomplete="off">
I don't use any JavaScript events that are triggered when the focus changes.
Appreciate any insights.
I'm not sure this adds any value to anyone other than it's worth double checking your code for rogue event handlers.
I found this buried in an included file:
window.addEventListener('keyup', function(evt) { keyboardUp(evt); }, false);
and the associated function had a scenario where it could return false:
function keyboardUp(e)
{
var key;
if (window.event) // IE
{
key = e.keyCode;
}
else if(e.which)
{
key = e.which;
}
if (key === 18 && g.altkey === false) { g.altkey = true; return; }
if (g.altkey === false) return;
...
}
Pretty sloppy on my part.
Not sure why this should be an issue switching focus but it does at least solve my problem.

trigger active form validation manually before submit

is it possible to call the active form validation programmatically via javascript? I need to call the validation procedure before doing some ajax operations.
Guess I'm a bit late with a reply here but I just had the same question and the solution by soju did not work for me either.
So I looked a bit deeper into the JS-code of ActiveForm and found that it appears to monitor the status of each field in a variable and if the field is "untouched" the validation isn't triggered, unless submitting the actual form. So I changed my call to this:
var $form = $("#my-form"),
data = $form.data("yiiActiveForm");
$.each(data.attributes, function() {
this.status = 3;
});
$form.yiiActiveForm("validate");
This now appears to be working as I expect.
We can achieve that by merging #BlueZed and #S Rana's answer.
You can write below script, so we can check that if form has any error in it then form will not submit (Even It will work for tabular (wizards) like form ).
var $form = $("#form"),
data = $form.data("yiiActiveForm");
$.each(data.attributes, function() {
this.status = 3;
});
$form.yiiActiveForm("validate");
if ($("#form").find(".has-error").length) {
return false;
}
Thanks blue zed,
but before this -
to append form field, u need to do this stuff...
// your input
$inputData = $form->field($model,"prductName");
// this remove next line & convert double quotes to single quotes
$newInputData= trim(preg_replace('/\s+/', ' ',str_replace('"',"'", $inputData)));
// then append like this
$("#table").append("'.$newInputData.'");
// this worked for me along with blue zend solution like this below
$this->registerJs('
$(document).on("click","input[type=text]",function(){
var $form = $("#w0"),
data = $form.data("yiiActiveForm");
$.each(data.attributes, function() {
this.status = 3;
});
$form.yiiActiveForm("validate");
});
');
Yes it is possible, you should try this :
$('#form-id').yiiActiveForm('validate');
this is worked for me
$this->registerJs( "
$('body').on('beforeSubmit', 'form#product-form', function () {
var form = $(this);
// return false if form still have some validation errors
if (form.find('.has-error').length) {
return false;
}
// submit form
$.ajax({
url: form.attr('action'),
type: 'post',
data: form.serialize(),
success: function (response) {
}
});
return false;
}); ");
The validation is activated when submitting the form. Thus, this will work:
$form.data('yiiActiveForm').submitting = true;
$form.yiiActiveForm('validate', false);
The second argument to validate is called forceValidate.
To validate manually from javascript, you should place following code to end of form submit event.
return $('#your-form-id').yiiActiveForm('validate');
For novice users,
$('#your-form-id').submit(function () {
return $('#your-form-id').yiiActiveForm('validate');
});
Also note that you should specify form id on ActiveForm like below
<?php $form = ActiveForm::begin(['id' => 'd4d-hub-form']); ?>
I had the same issue. And the are no clearly solution in official documentation and I don't know why any solution on Stackoverflow does not work for me. May be in the different versions of yii2 there is different ways to do that. I have spent a lot of time to find solution. In my case I have triggered validation for individual input on the form:
$('#form-id').data('yiiActiveForm').submitting = false;
$('#form-id').yiiActiveForm('validateAttribute', 'input-id'); //this will triger validation for input with id 'input-id'
$('#form-id').yiiActiveForm('validateAttribute', 'other-input-id'); //this will triger validation for input with id 'other-input-id'
please notice second parameter of function yiiActiveForm() it is not selector and it is not name of attribute it is id of input of attribute!!!
Try this
$("#form-id").data('yiiActiveForm').submitting = true;
$("#form-id").yiiActiveForm('validate');
it will show validation error if any field is not valid.
Also if all fields are validate then it will submit the request

How to make two checkboxes required out of three in HTML?

<input type="checkbox" name="Package1" value="packagename">
<input type="checkbox" name="Package2" value="packagename">
<input type="checkbox" name="Package3" value="packagename">
How to make any two checkboxes required for the user to submit the form. The user should not be able to submit the form unless he has checked atleast two checkboxes?
How to achieve that?
Rename checkboxes to name=package[] and values 1, 2, 3.
Then in PHP you'll have o condition (if you send form with GET method, just change POST to GET):
if (isset($_POST['package']) && count($_POST['package']) >= 2) {/* continue */}
If you want to validate it in browser (JS), than:
<script>
var i = 0;
$('[type="checkbox"]').each(function() {
if ($(this).is(':checked')) {
i++;
}
});
if (i <= 1) {
return false; // disable sending form when you've checked 1 checkbox in maximum
}
</script>
Add a class that refers only these checkboxes and then count how many are checked.
A quick and dirty way to validate the checkboxes using JavaScript:
JavaScript
checkCheckboxes = function() {
var numberOfCheckedCheckboxes = 0;
var checkbox1 = document.getElementsByName("Package1")[0];
var checkbox2 = document.getElementsByName("Package2")[0];
var checkbox3 = document.getElementsByName("Package3")[0];
if (checkbox1.checked)
{
numberOfCheckedCheckboxes++;
}
if (checkbox2.checked)
{
numberOfCheckedCheckboxes++;
}
if (checkbox3.checked)
{
numberOfCheckedCheckboxes++;
}
alert(numberOfCheckedCheckboxes >= 2);
}
DEMO: JSFiddle
This code isn't the cleanest block of code, however it does get the job done, and will return true if there are at least 2 checkboxes checked, and will return false otherwise. To make it cleaner, you can change the name value of each checkbox to the same name, such as "packages", and then use document.getElementByName("packages"), then use a for-each loop to loop through each element and check its checked state (I would provide a demo in JSFiddle or JSBin, however it seems that Google Chrome is blocking the script in that case). Using the for-each implementation would allow you to use the same amount of code, regardless of the number of checkboxes.
In HTML, you cannot.
You can impose restrictions in client-side JavaScript or in server-side processing of form data, or both. As usual, client-side restrictions are inherently unreliable and should be regarded as convenience to the user, not a reliable method of doing anything. Server-side processing depends on the server-side technology used.

How To Make an INPUT Field As "Required" In HTML5?

On my website I have a reservation forum,
and I put that the person cannot submit the forum unless submitting their name and phone number.
<p><label>Phone #:<input type="text" id="phone" name="phone" placeholder="###-###-####" style="margin:10px; width:100px; height:15px" required>
It works perfect on every device besides any mobile device using safari, so I wanted to know what code can I use so it can work on all devices.
Any input/help/advice would be appreciated.
Mobile Safari validation isn't really up to par compared to all the other browsers. You can check out feature support by going to Can I use. What I would do to fix this issue is grab Modernizr.js or use some other feature detection to find out if form validation is supported. If it isn't, then just put it in a little JS snippet saying that the field is required.
Something like this should do if you use Modernizr.js and select "Input Attributes" under HTML5.
var jsRequired;
if (!Modernizr.input.required) {
jsRequired = true;
}
Then on the form submission:
$('#form-submit').on('click', (function(evt) { // this is the form submit button
evt.preventDefault(); // preventing reload of the page
if (jsRequired == true) {
var requiredInputs = $('input[required]');
for (var i = 0; i < requiredInputs.length; i++) {
if (requiredInputs[i].value == '') {
$('#submission-info').text('Whoa whoa whoa, you missed one...');
// highlight the missed one by adding a class
requiredInputs[i].className += " submission-error";
return false; //; stop the rest of the submission
}
}
}
var formData = $('form#contact-form').serialize(); // serialize data
$.ajax({
url: 'mail.php', // rename this to your php file
type: 'POST',
data: formData
}).done(function(response) {
// do stuff to to show the user that the form was submitted
$('#submission-info').text('Success, your information has been sent to us (and the NSA of course) and we will reply to you as soon as possible.');
}).fail(function(response, error) {
// tell the user what happened that caused the form submission to fail
$('#submission-info').text('Oh no, something happened. Maybe try again?');
});
});
Some of the code should be changed around to fit your stuff but otherwise it should be in the general direction of what you are looking to do.

With HTML5 url input validation assume url starts with http://

HTML5 provides for automatic URL validation :-
<form>
<input type="url" name="someUrl">
</form>
This will fail validation for URL's that don't have a protocol prefix - e.g. stackoverflow.com will fail while http://stackoverflow.com will pass.
How can I automatically add http:// to a url if there isn't already a protocol?
I could add a onblur event handler but is there a better way like some before validation event?
The code for this should not interrupt the user's action, but should instead wait until the user leaves the form field to check the input text for "http". So use "onblur" instead of "onkeyup".
Then, just see if the string contains "http" using indexOf. If not, it will return -1, which is falsey.
function checkURL (abc) {
var string = abc.value;
if (!~string.indexOf("http")) {
string = "http://" + string;
}
abc.value = string;
return abc
}
<form>
<input type="url" name="someUrl" onblur="checkURL(this)" />
<input type="text"/>
</form>
Fiddle
if you don't want the browser validation (it can vary between browsers) you can add the following novalidate attribute
<input type="url" name="someUrl" formnovalidate="formnovalidate">
else you might want to be more transparent about prefixing http:// by simply adding once someone starts to type or even to have http:// already typed into the box on the page load
(credit to editor who rightly points out that novalidate applies to form, while above overrides that, debit to creditor for approach to edit ;)
what you guys probably want to use is this:
$(function(){
$('input[type="url"]').on('blur', function(){
var string = $(this).val();
if (!string.match(/^https?:/) && string.length) {
string = "https://" + string;
$(this).val(string)
}
});
});
this runs on document ready
checks if value is empty or has missing http at the beginning
inserts it in that case on blur
thanks #1j01
you can use
HTML :
<form>
<input type="url" name="someUrl" onkeyup="checkUR(this)" >
</form>
SCRIPT:
function checkUR(abc){
string = abc.value
if(!(/^http:\/\//.test(string))){
string = "http://" + string;
}
abc.value=string
}
example
I hope it will help
You can try to force users enter valid url by providing initial value and placeholder.
<label for="some-url">Some url:</label>
<input id="some-url" type="url" placeholder="http://example.com" value="http://">
Using the URL class would be even better.
function validateUrl(value) {
try {
const currentUrl = new URL(value);
const { protocol } = currentUrl;
if (protocol !== 'http:' && protocol !== 'https:') {
currentUrl.protocol = 'http:';
return currentUrl.toString();
}
} catch(e) {
return `http://${value}`;
}
}
The advantage here is that you check for any protocol first. In case the user mistyped the protocol (e.g. htts:), it will be replaced by http:. The answers above would all prepend a new protocol which would result in something like http://htts:. In case there is no protocol it will just prepend http:// in the catch block.
One-liner:
<input type="url" onblur="if (!~this.value.indexOf('http')) this.value = 'https://' + this.value">
It will help users with http prepending annoyance without being intrusive. Just add this JavaScript code to your webpages with type="url" <input> elements, and everything will work automatically.
// Run a callback function after DOM is fully loaded
function domReady(callback) {
if (document.readyState != "loading") {
callback();
} else {
document.addEventListener("DOMContentLoaded", callback);
}
}
// Prepend https to url input field value if already not prepended by http or https
domReady(() => {
const urlInput = document.querySelectorAll('input[type="url"]');
for(i = 0; i < urlInput.length; i++) {
urlInput[i].addEventListener('change', function(){
let urlValue = this.value;
// If http or https isn't prepended as case insensitive characters and if the input field has any value
if (!urlValue.match(/^https?:/i) && urlValue.length) {
urlValue = "https://" + urlValue;
this.value = urlValue;
}
});
}
});
Advantages
prepending https:// if http or https isn't already prepended
in the input field value
prepending https:// even when there is http or https that isn't in the beginning
automatically modifying value after users leave input field
not adding https:// if input field has no value
working in a case insensitive manner
automatically working on all url type input fields without requiring to modify HTML input field elements
Limitations
adding https:// in front of valid urls that start with any schemes
other than http or https such as ftp and tel which will cause those valid URLs to not work
PS: If you also want to change http to https, append this else if statement to the last if statement in the previous code.
else if (urlValue.match(/^http:/i)) {
urlValue = urlValue.replace(/^http:/i, "https:");
this.value = urlValue;
}
This will prepend the URL before submitted if it does not have a http or https in the URL. It is also case insensitive (the i at the end). I'm also using onchange instead of the other events to account for users pressing the enter key and submitting the form that way.
SCRIPT:
function checkURL(o) {
if (!/^https?:\/\//i.test(o.value)) {
o.value = "http://" + o.value;
}
}
ALTERNATE SCRIPT: (Always correct to "http://")
function checkURL(o) {
o.value = o.value.replace(/^(https?:\/\/)?/i, "http://");
}
HTML:
<form>
<input type="url" name="someUrl" onchange="checkURL(this)" >
</form>