How to add required attribute on contact form 7? - contact-form

I want to add required attribute additionally on contact form.
Screenshots
<textarea name="your-message" required="required" cols="40" rows="10" class="wpcf7-form-control wpcf7-textarea wpcf7-validates-as-required" id="your-message" aria-required="true" aria-invalid="false"></textarea>
How can I do in backend form?
[textarea* your-message id:your-message] <label for="your-message">Message</label>
Please help me.
Thanks

If you're trying to add the html5 required attribute to a form tag in Contact Form 7. You can filter the form content and include it. However, since the form submission is ajax, it won't really do anything unless you disable that also.
You can use the hook wpcf7_form_elements to filter the output and do a find/replace.
By looking for name="your-field-name" you specify the input / textarea tag vs the span that wraps the form tags.
<?php
// Filter Form Elements
// Include in your child theme/theme's functions.php
add_filter( 'wpcf7_form_elements', 'dd_wpcf7_form_elements_replace' );
function dd_wpcf7_form_elements_replace( $content ) {
// $name == Form Tag Name [textarea* your-message]
$name = 'name="your-message"';
$str_pos = strpos( $content, $name );
if (false !== $str_pos) {
$content = substr_replace( $content, ' required="required" ', $str_pos, 0 );
}
return $content;
}
This above will output.
<textarea required="required" name="your-message" cols="40" rows="10" class="wpcf7-form-control wpcf7-textarea" aria-invalid="false"></textarea>

This should do it:
<label> Your Message (required) [text* your-message] </label>

Related

AngularJS - perform extra validation on form submit

I've been googling for a while and can't seem to find a good answer for my specific case. I've found ways to do real-time validations but I want to combine that with some custom validations after a user clicks on "submit". I want to allow the user to still click on the submit even if it's not valid but then I'll cancel the submission in the code. Take the following code:
<form name="cashForm" id="cashForm" novalidate>
<input type="text" id="name" required /> //
<input type="number" placeholder="Tax: " required name="tax" id="tax" />
<input type="number" placeholder="Tip: " required name="tip" id="tip" />
<button ng-click="submission()" ng-disabled="paymentForm.$invalid">Submit</button>
</form>
//inside controller
this.submission = function() {
//check if tip + tax is over 20
//prevent form and show error message if not
//otherwise allow default behavior
}
So I only want the form to actually submit if the tax/tip is over 10. How do I check for this and how do I prevent the form submission if it doesn't meet the requirements? Also, would I put this logic in the controller?
It looks pretty close to what you're after to me. Just a couple of things...
Add ng-model directives to your input controls to create two-way data-bindings that you can pick up and use in your controller:
<form name="cashForm" id="cashForm" novalidate>
<input id="name" name="name" type="text" ng-model="nameValue" required />
<input id="tax" name="tax" type="number" ng-model="taxValue" placeholder="Tax: " required />
<input id="tip" name="tip" type="number" ng-model="tipValue" placeholder="Tip: " required />
<button
ng-click="submission()"
ng-disabled="paymentForm.$invalid">
Submit
</button>
Inject $scope into your controller to allow you to pick up those ng-model bindings in your controller's submission method:
function submission() {
$scope.errorMsg = "";
if ($scope.taxValue <= 10) {
$scope.errorMsg = "tax not greater than 10";
return;
}
if ($scope.tipValue <= 10) {
$scope.errorMsg = "tip not greater than 10";
return;
}
// If you reached here your post-click validation passed,
// so continue to submit the data...
}
You could then display an error message using the ng-if directive with a css class that highlights the error message:
<div ng-if="!!errorMessage" class="text-danger">
{{ errorMessage }}
</div>
Finally, once you've cracked using $scope in your controller you might want to read about the perceived evils of using $scope and consider switching to controller-as syntax instead. Check out John Papa's Blog Post AngularJS's Controller As and the vm Variable

Retrieve data for an autocomplete form input with angular

I have a form made with angular, one of the inputs is autocompleted with google maps. The problem is that if I write "Mad" and the autocomplete fills it with "Madrid" when the form is sent there is only "Mad" instead of "Madrid" and the same for longer addresses.
I had a similar problem autofilling the latitude and longitude obtained with the place of the autocomplete, but I solved it. I tried the same with the autocomplete input and is not working.
This is part of my form:
<fieldset class="form-group">
<input ng-model="newCtrl.event.formatted_addres" type="text"
ID="location-placheholder" class="form-control"
placeholder="Where will be the event?"
title="Location" required />
</fieldset>
<fieldset ng-show ="false" class="form-group">
<input ng-model="newCtrl.event.longitude" type="float"
ID="location-longitude" class="form-control"
title="Location-longitude" required />
</fieldset>
<fieldset ng-show ="false" class="form-group">
<input ng-model="newCtrl.event.latitude" type="float"
ID="location-latitude" class="form-control"
title="Location-latitude" required />
</fieldset>
and this is the autocomplete function for the formatted_address field:
function setupAutocomplete(){
var input = $('#location-placheholder')[0];
var autocomplete = new google.maps.places.Autocomplete(input);
autocomplete.addListener('place_changed', function(){
var place = autocomplete.getPlace();
var infowindow = new google.maps.InfoWindow({
});
if (place.geometry.location) {
$("#location-longitude").val(place.geometry.location.lng().toFixed(7));
$("#location-longitude").trigger('input');
$("#location-latitude").val(place.geometry.location.lat().toFixed(7));
$("#location-latitude").trigger('input');
$("location-placeholder").val(place.formatted_address);
$("location-placeholder").trigger('input');
map.setCenter(place.geometry.location);
createMarker(place.geometry.location, place.formatted_address);
} else {
alert("The place has no location...?")
};
});
};
When I do
$("#location-latitude").val(place.geometry.location.lat().toFixed(7));
$("#location-latitude").trigger('input');
The input of latitude fills correctly and is sent correctly, but if I do:
$("location-placeholder").val(place.formatted_address);
$("location-placeholder").trigger('input');
It keeps sending only the part of the address that I have already written, not the rest of the address filled with the autocomplete.
Thanks
I add a fiddle with my code, I've been trying to make it work without the $http requests, but I couldn't. So I hope this is enough to evaluate my code.
http://jsfiddle.net/sjc7jtbp/1
Finally I solved it, for some reason ajax was not targeting the input. So I created a new input hidden with ng-show="false" and I labelled it as class="autofill".
So later I aimed at it as $('.autofill') and it worked. The rest is submit this input and not the original one. Maybe it is not an elegant solution, but it works.

parsley js - conditional required if checkbox checked

Is there an easy way with parsleyjs to make a field required depending on another field?
See my js fiddle here http://jsfiddle.net/marksteggles/wbhLq0t4/1/
<form data-parsley-validate="true">
<div class="form-group">
<label>
<input name="request_signature" type="checkbox" />Require signature</label>
<div class="request_signature_fields">
<textarea class="form-control required" name="signature_reason" rows="3"></textarea>
</div>
</div>
<input class="btn btn-success" name="commit" type="submit" value="Send" />
</form>
Minimally as of 2.2.0 you can create a custom validator:
window.Parsley.addValidator("requiredIf", {
validateString : function(value, requirement) {
if (jQuery(requirement).val()){
return !!value;
}
return true;
},
priority: 33
})
This gets applied in such a way:
<textarea
class="form-control required"
name="signature_reason"
rows="3"
data-parsley-validate-if-empty="true"
data-parsley-required-if="#my-field-to-check"
></textarea>
Explanation
data-parsley-required-if is the custom validator we just defined. It takes any arbitrary jQuery selector and if that field contains a non-falsy value it ensures that this field is not empty.
data-parsley-validate-if-empty is needed to ensure that the field is being validated at all, because Parsley does not validate empty non-required fields by default.
More data on custom validators here: http://parsleyjs.org/doc/index.html#custom
There is no easy way yet (see this and this).
You can either toggle the attribute required with Javascript, or listen to the right parsley events on one field and check the other field.
Just incase anyone else is trying to work this out. The best way does seem to be altering the required attribute then clearing the values.
I used this:
HTML:
<input id="checkbox-id" type="checkbox">
<div id="conditional-inputs" style="display:none;">
<input type="text" name="somename" />
<input type="text" name="othername" />
<input type="text" name="onemoreforluck" />
</div>
jQuery:
$("#checkbox-id").change(function() {
if(this.checked) {
$('#conditional-inputs').slideDown();
/* use .slideDown to display conditional input block */
$("#conditional-inputs :input").prop('required', true);
/* set required attribute on all inputs inside conditional area */
}
else{
$('#conditional-inputs').slideUp();
/* use .slideUp to hide conditional input block */
$("#conditional-inputs :input").prop('required', false).val('');
/* remove required attribute on all inputs and empty values of inputs */
}
})
I realise that this question was asked and answered in 2012, and is most likely related to the ParsleyJS v1, while the most recent version at the time of writing this is v2.2.0. However I had to do some work on an old form that used v1 and I found that conditionals are possible (with a little bit of jQuery). So here's to anyone who might still need this.
You can dynamically add and remove form elements and constraints (read: validation rules) using the following:
$('#form').parsley('addItem', '#input_id');
$('#form').parsley('removeItem', '#input_id');
$('#input_id').parsley('addConstraint', '{ required: true }');
$('#input_id').parsley('removeConstraint', 'required');
So using jQuery listeneners for when the checkbox changes we can execute this kind of code which will add the signature field as a required field. Here it is in action for the question.
< script src = "js/parsley-v1.js" > < /script>
<script>
$('#request_signature').on('click', function() {
if($(this).is(':selected')) {
$('#signature_form').parsley('addItem', '#signature_reason');
$('#signature_reason').parsley('addConstraint', { required: true });
} else {
$('#signature_reason').parsley('removeConstraint', 'required' });
$('#signature_form').parsley('removeItem', '#signature_reason');
}
});
</script >
<form id="signature_form" data-parsley-validate="true">
<div class="form-group">
<label>
<input id="request_signature" name="request_signature" type="checkbox" />Require signature</label>
<div class="request_signature_fields">
<textarea id="signature_reason" class="form-control" name="signature_reason" rows="3"></textarea>
</div>
</div>
<input class="btn btn-success" name="commit" type="submit" value="Send" />
</form>
You can also hide the parts that are not required anymore, or disable the fields that are not needed, and add [disabled] and :hidden to the excluded Parsley option.
{
excluded: 'input[type=button], input[type=submit], input[type=reset], input[type=hidden], [disabled], :hidden',
}
NB: you don't need to hide each field, hiding a parent div is enough.
I found a good example that I forked here
➡️ http://jsfiddle.net/capripot/xoaLs4bt/
This should be possible with the great little Parsley addon plugin found here: http://themonk.github.io/parsely-conditions/
I found the shortest method -
$('input[type=radio][name=nlcsu]').change(function() {
// I am checking for a Radio button
if (this.value == 1) {
$("#nlcsu_post").attr('required', '1');
$("#nlcsu_year").attr('required', '1');
} else if (this.value == 0) {
$("#nlcsu_post").removeAttr('required');
$("#nlcsu_year").removeAttr('required');
}
});

Angular.js: Set form fields "dirty" upon submission

How can I make a form input to become dirty as the form is submitted?
This is needed so that the input fields with an $error can be
Example:
name: <input type="text"
ng-model="user.name"
ng-model-options="{ updateOn: 'blur' }"
name="uName"
required /><br/>
As the form is submitted, I want this field - if left blank - to be rendered using the "invalid & dirty" style:
.css-form input.ng-invalid.ng-dirty {
background-color: #FA787E;
}
Disable the submission button until form is dirty and the form items are valid.
<button type="submit" class="btn btn-primary" ng-disabled="myFrmName.$invalid || !myFrmName.$dirty">Submit Form</button>
Using ng-disabled will disable the form submission button while the form is $invalid or the form has yet to be touched (not $dirty).
EDIT
I usually do something like this to display an error next to the required field:
<input type="text" name="myField" required ng-class="{true : 'has-error'}[hasError(myFrmName.myField.$error.required,myFrmName.myField.$dirty)]>
<span ng-if="hasError(myFrmName.myField.$error.required,myFrmName.myField.$dirty)">Required!</span>
Then in your controller:
$scope.hasError = function(e,d){ // e = $error, d = $dirty
if(angular.isDefined(e))
return e && d;
return false;
} // end hasError
Example with ngMessages (Angular 1.3)
<input type="text" name="myField ng-model="fields.myField" ng-class="{true : 'has-error'}[hasError(myFrmName.myField.$error.required,myFrmName.myField.$dirty)] required>
<ng-messages for="myFrmName.myField.$error" ng-if="myFrmName.myField.$dirty">
<ng-message when="required" class="text-danger">The field is required!</ng-message>
</ng-messages>
The great thing about ngMessages is that all you need to do is add more <ng-message> tags for each type of validation for the field and just change the when attribute approrpriately.
<ng-message when="minlength">Your entry is too short.</ng-message>
Angular will display the correct message based upon whether or not the when is in the $error object for the field.
You can use $submitted flag of the form to highlight the field if the form is submitted and is empty.
<input type="text"
ng-model="user.name"
ng-model-options="{ updateOn: 'blur' }"
name="uName"
ng-class={'has-error': yourFormName.$submitted && !yourFormName.uName.$valid}
required />
Or I guess just setting the form's dirty flag to true in your controller might do the same work. But I believe this implicitly changes the DOM as it adds a class to form which is not a good practice in angular.
$scope.yourForm.$dirty = true;
in case you would like to do that programatically, there is a method named "$setDirty()" you could use for that purpose.
https://docs.angularjs.org/api/ng/type/form.FormController

Show ? in textbox when textbox have ng-pattern for numeric validation

I need to show '?' when the value not able to read from scanner which returns me value by including '?'
Let say document has sr no as '123' but let say for some reason scanner not able to read it then it returns me as "12?" or "???" or "?23" or "1?3"
If any digit which is not readable that need to corrected by user manually for that i need to show them in to the textbox.
In our application we are using angularjs validations, which are not allowing me to show above values inside textbox as it contains '?' which is not numeric value.
Also I should enforce the numeric validation so that user can correct the above and submit to the server.
So how we achieve this functionality ?
<div ng-app ng-controller="formCtrl">
<form name="myForm" ng-submit="onSubmit()">
<input type="text" ng-model="price" name="price_field" ng-pattern="/^[0-9]{1,7}$/" required>
<span ng-show="myForm.price_field.$error.pattern">Not a valid number!</span>
<input ng-show="toggle" type="submit" value="submit"/>
<input ng-show="!toggle" type="button" ng-click="AfterProcessing()" value="After Processing"/>
<input type="button" value="Reset" ng-click="reset()"/>
<br/>
<span>Activity : {{message}}</span>
</form>
</div>
JS code
function formCtrl($scope){
$scope.price= "123";
$scope.toggle = false;
$scope.message="No Activity";
$scope.onSubmit = function(){
$scope.toggle=false;
$scope.message="onSubmit clicked...";
}
$scope.AfterProcessing = function(){
$scope.toggle=true;
$scope.price ="1?3";
$scope.message="AfterProcessing clicked...";
}
$scope.reset=function()
{
$scope.toggle=false;
$scope.price ="123";
$scope.message="Reset clicked...";
}
}
I have created sample as below.
Plz check on JsFiddle sample
-Thanks
You need to create a CSS Class that will be applied to text box. Using :before and :after pseudo css construct, you can add ? character and get desired result.
So,
1. Define a CSS Class with :before and/or :after as per your requirement
2. On the HTML, use ng-class="{'your-class': $error, 'regular-class': '$pristine'}"
Let me know if you need a code sample and a plunker. (I am at the end of the day. May be will provide some code tomorrow. )
If you can create a plnkr based on above and submit link here, more people would be able to help you. thanks.

Resources