I'm doing a custom validation for an ISBN number, I already have the function that checks the number and works perfect giving me the response by console, but I need to do the custom validator to get the error in the view with the form control and in this step this error is showing in console when I write an ISBN number, It's like it checks the errors but it doesn't know when its right and it should take the null response as a right ISBN number, at least thats what I saw in some examples.
core.js:6210 ERROR TypeError: Cannot read properties of null (reading 'CheckDigit')
at LibrosComponent_Template (libros.component.html:22)
at executeTemplate (core.js:9600)
at refreshView (core.js:9466)
at refreshComponent (core.js:10637)
at refreshChildComponents (core.js:9263)
at refreshView (core.js:9516)
at refreshEmbeddedViews (core.js:10591)
at refreshView (core.js:9490)
at refreshComponent (core.js:10637)
at refreshChildComponents (core.js:9263)
This is my typescript,
export class LibrosComponent implements OnInit {
//ISBN Validator
isbnValue: string = ""
firstFormGroup: FormGroup;
secondFormGroup: FormGroup;
constructor(
private _formBuilder: FormBuilder,
) {}
ngOnInit() {
this.firstFormGroup = this._formBuilder.group({
tituloControl: ['', Validators.required],
isbnControl: ['', Validators.required],
},
{ validator: this.isbnValidate });
}
isbnValidate(g: FormGroup) {
var isbnValue = g.get('isbnControl').value
var subject = isbnValue;
// Checks for ISBN-10 or ISBN-13 format
var regex = /^(?:ISBN(?:-1[03])?:? )?(?=[0-9X]{10}$|(?=(?:[0-9]+[- ]){3})[- 0-9X]{13}$|97[89][0-9]{10}$|(?=(?:[0-9]+[- ]){4})[- 0-9]{17}$)(?:97[89][- ]?)?[0-9]{1,5}[- ]?[0-9]+[- ]?[0-9]+[- ]?[0-9X]$/;
if (regex.test(subject)) {
// Remove non ISBN digits, then split into an array
var chars = subject.replace(/[- ]|^ISBN(?:-1[03])?:?/g, "").split("");
// Remove the final ISBN digit from `chars`, and assign it to `last`
var last = chars.pop();
var sum = 0;
var check, i;
if (chars.length == 9) {
// Compute the ISBN-10 check digit
chars.reverse();
for (i = 0; i < chars.length; i++) {
sum += (i + 2) * parseInt(chars[i], 10);
}
check = 11 - (sum % 11);
if (check == 10) {
check = "X";
} else if (check == 11) {
check = "0";
}
} else {
// Compute the ISBN-13 check digit
for (i = 0; i < chars.length; i++) {
sum += (i % 2 * 2 + 1) * parseInt(chars[i], 10);
}
check = 10 - (sum % 10);
if (check == 10) {
check = "0";
}
}
if (check != last) {
return null;
} else {
return g.get('isbnControl').setErrors( {CheckDigit: true} )
}
} else {
return g.get('isbnControl').setErrors( {Invalid: true} );
}
}
}
In my HTML I have some inputs that are included in the form:
<form class="form" [formGroup]="firstFormGroup">
<div class="container-1">
<mat-form-field class="width">
<mat-label>TÃtulo</mat-label>
<input matInput formControlName="tituloControl" required>
</mat-form-field>
<mat-form-field class="width">
<mat-label>ISBN</mat-label>
<input matInput formControlName="isbnControl" required>
<mat-error *ngIf="firstFormGroup.controls['isbnControl'].pristine || firstFormGroup.controls.isbnControl.errors['CheckDigit']">Invalid ISBN check digit</mat-error>
<mat-error *ngIf="firstFormGroup.controls['isbnControl'].pristine || firstFormGroup.controls.isbnControl.errors['Invalid']">Invalid ISBN</mat-error>
</mat-form-field>
</form>
I already found the solution to the error, replacing the .errors [''] with hasError (''), the .errors[] is to read the property of the object that contains the validation error. But first I have to evaluate with the hasError () method if that property exists to access it.
Related
I have lots of checkbox element on my Grails form, one is this:
<g:checkBox id="consolidate" name="consolidate" value="${true}" checked="${false}" />
Then on the receiving controller, I verify the value of the checkbox using this code:
println params?.consolidate
And it displays:
on
Regardless whether I've tick my checkbox or not. In other language, if the checkbox is not ticked, its value on the controller will be null or undefined. What should be its value when unchecked, and what is the right code to access its value on the grails controller?
Temporary Solution:
The following code (on JavaScript) is what I had used temporarily to accommodate my requirement. Though what I want is an explanation or maybe correction about this behavior.
var serialized_string = "";
$("#form input").each(function(i, j) {
var o = $(j);
if(o.val() !== undefined && o.val() !== "undefined" && o.val() !== "") {
if(serialized_string === "") {
serialized_string += o.attr("name") + "=";
}
else {
if(o.attr("name") === "consolidate") {
var val = "false";
if(o.prop("checked")) {
val = "true";
}
data += val;
}
else {
data += "&" + o.attr("name") + "=";
}
}
}
});
If checked, you see the on you're seeing; otherwise you see null, which is your false.
I'm using select2 with Bootstrap 3.
Now I would like to know whether it is possible to display all optgroup items if the search matches the optgroup name while still being able to search for items as well. If this is possible, how can I do it?
The above answers don't seem to work out of the box with Select2 4.0 so if you're hunting for that, check this out: https://github.com/select2/select2/issues/3034
(Use the function like this: $("#example").select2({matcher: modelMatcher});)
function modelMatcher (params, data) {
data.parentText = data.parentText || "";
// Always return the object if there is nothing to compare
if ($.trim(params.term) === '') {
return data;
}
// Do a recursive check for options with children
if (data.children && data.children.length > 0) {
// Clone the data object if there are children
// This is required as we modify the object to remove any non-matches
var match = $.extend(true, {}, data);
// Check each child of the option
for (var c = data.children.length - 1; c >= 0; c--) {
var child = data.children[c];
child.parentText += data.parentText + " " + data.text;
var matches = modelMatcher(params, child);
// If there wasn't a match, remove the object in the array
if (matches == null) {
match.children.splice(c, 1);
}
}
// If any children matched, return the new object
if (match.children.length > 0) {
return match;
}
// If there were no matching children, check just the plain object
return modelMatcher(params, match);
}
// If the typed-in term matches the text of this term, or the text from any
// parent term, then it's a match.
var original = (data.parentText + ' ' + data.text).toUpperCase();
var term = params.term.toUpperCase();
// Check if the text contains the term
if (original.indexOf(term) > -1) {
return data;
}
// If it doesn't contain the term, don't return anything
return null;
}
Actually found the solution by modifying the matcher opt
$("#myselect").select2({
matcher: function(term, text, opt){
return text.toUpperCase().indexOf(term.toUpperCase())>=0 || opt.parent("optgroup").attr("label").toUpperCase().indexOf(term.toUpperCase())>=0
}
});
Under the premise that the label attribute has been set in each optgroup.
Found a solution from select2/issues/3034
Tested with select2 v.4
$("select").select2({
matcher(params, data) {
const originalMatcher = $.fn.select2.defaults.defaults.matcher;
const result = originalMatcher(params, data);
if (
result &&
data.children &&
result.children &&
data.children.length
) {
if (
data.children.length !== result.children.length &&
data.text.toLowerCase().includes(params.term.toLowerCase())
) {
result.children = data.children;
}
return result;
}
return null;
},
});
A few minor changes to people suggested code, less repetitive and copes when there are no parent optgroups:
$('select').select2({
matcher: function(term, text, opt){
var matcher = opt.parent('select').select2.defaults.matcher;
return matcher(term, text) || (opt.parent('optgroup').length && matcher(term, opt.parent('optgroup').attr("label")));
}
});
I'm having a problem where my dynamically generated html is getting escaped and outputed on the screen. heres what I have:
#{
string TrialMessage = string.Empty;
if ((bool)ViewBag.msd.IsOnTrial == true)
{
var expDate = (DateTime)ViewBag.msd.RenewalDate;
var daysToTrialExpiation = expDate.AddDays(1) - System.DateTime.UtcNow;
TrialMessage = "<b>Trial Ends in: <span style=\"color:[Color];\">" + (daysToTrialExpiation.Days) + "</span> Days</b>";
if (daysToTrialExpiation.Days > 5)
{
TrialMessage = TrialMessage.Replace("[Color]", "green");
}
else if (daysToTrialExpiation.Days > 2)
{
TrialMessage = TrialMessage.Replace("[Color]", "orange");
}
else if (daysToTrialExpiation.Days > 0)
{
TrialMessage = TrialMessage.Replace("[Color]", "red");
}
else
{
TrialMessage = "<b style=\"color: red;\"> Trial Ended " + Math.Abs(daysToTrialExpiation.Days) + " Days Ago</b>";
}
}
}
When I use the TrialMessage in the View, I'm getting the escaped version of it outputted on the screen:
<b>Trial Ends in: <span style="color:green;">15</span> Days</b>
I have tried to use Html.Raw(TrialMessage) I've even tried to manually create an HTMLString with the same result. What am I missing?
Update: The way I'm outputting it on the view is:
#Html.Raw(TrialMessage)
In an effort to just get it working (it seems you're pressed for time) what if you removed html from the variable?
Perhaps something like this could work for you:
#{
string trialColor = string.Empty;
int trialDays = 0;
if ((bool)ViewBag.msd.IsOnTrial)
{
var expDate = (DateTime)ViewBag.msd.RenewalDate;
var trialDays = (expDate.AddDays(1) - System.DateTime.UtcNow).Days;
if (trialDays > 5)
{
trialColor = "green";
}
else if (trialDays > 2)
{
trialColor = "orange";
}
else
{
trialColor = "red";
}
}
}
...
#if((bool)ViewBag.msd.IsOnTrial && trialDays > 0)
{
<strong>Trial Ends in: <span style="color:#trialColor;">#trialDays </span> Days</strong>
} else if((bool)ViewBag.msd.IsOnTrial) {
<strong style="color: red;">Trial Ended #Math.Abs(trialDays) Days Ago</strong>
}
Note: untested code. It's been a bit since I've written razor.
I am trying to do a simple CRUD app using Ember + Rails and I'm getting the following error when trying to go to the /workouts route.
Error while loading route: TypeError {} ember.js?body=1:415
Uncaught TypeError: Object function () {
if (!wasApplied) {
Class.proto(); // prepare prototype...
}
o_defineProperty(this, GUID_KEY, undefinedDescriptor);
o_defineProperty(this, '_super', undefinedDescriptor);
var m = meta(this), proto = m.proto;
m.proto = this;
if (initMixins) {
// capture locally so we can clear the closed over variable
var mixins = initMixins;
initMixins = null;
this.reopen.apply(this, mixins);
}
if (initProperties) {
// capture locally so we can clear the closed over variable
var props = initProperties;
initProperties = null;
var concatenatedProperties = this.concatenatedProperties;
for (var i = 0, l = props.length; i < l; i++) {
var properties = props[i];
Ember.assert("Ember.Object.create no longer supports mixing in other definitions, use createWithMixins instead.", !(properties instanceof Ember.Mixin));
for (var keyName in properties) {
if (!properties.hasOwnProperty(keyName)) { continue; }
var value = properties[keyName],
IS_BINDING = Ember.IS_BINDING;
if (IS_BINDING.test(keyName)) {
var bindings = m.bindings;
if (!bindings) {
bindings = m.bindings = {};
} else if (!m.hasOwnProperty('bindings')) {
bindings = m.bindings = o_create(m.bindings);
}
bindings[keyName] = value;
}
var desc = m.descs[keyName];
Ember.assert("Ember.Object.create no longer supports defining computed properties.", !(value instanceof Ember.ComputedProperty));
Ember.assert("Ember.Object.create no longer supports defining methods that call _super.", !(typeof value === 'function' && value.toString().indexOf('._super') !== -1));
Ember.assert("`actions` must be provided at extend time, not at create time, when Ember.ActionHandler is used (i.e. views, controllers & routes).", !((keyName === 'actions') && Ember.ActionHandler.detect(this)));
if (concatenatedProperties && indexOf(concatenatedProperties, keyName) >= 0) {
var baseValue = this[keyName];
if (baseValue) {
if ('function' === typeof baseValue.concat) {
value = baseValue.concat(value);
} else {
value = Ember.makeArray(baseValue).concat(value);
}
} else {
value = Ember.makeArray(value);
}
}
if (desc) {
desc.set(this, keyName, value);
} else {
if (typeof this.setUnknownProperty === 'function' && !(keyName in this)) {
this.setUnknownProperty(keyName, value);
} else if (MANDATORY_SETTER) {
Ember.defineProperty(this, keyName, null, value); // setup mandatory setter
} else {
this[keyName] = value;
}
}
}
}
}
finishPartial(this, m);
this.init.apply(this, arguments);
m.proto = proto;
finishChains(this);
sendEvent(this, "init");
} has no method 'find'
My code is located here: https://github.com/ecl1pse/ember-workouts
What am I doing wrong?
Edit: Upon further investigation I believe the culprit is
EmberWorkouts.WorkoutsRoute = Ember.Route.extend(
model: -> EmberWorkouts.Workout.find()
This doesn't actually return anything. How do I debug from there?
If I replace that with this
EmberWorkouts.WorkoutsRoute = Ember.Route.extend
model: -> [{title: 'hi'}, {title: 'damn'}]
The view actually renders content.
How do I get the model to collect from Rails properly?
Ember Data's interface has changed a little with the current release:
You can clear out the store.js file entirely. Ember Data will automatically set up a data store for you using the REST Adapter (unless you tell it otherwise).
Use model: -> #store.find('workout') instead.
I tested this with your app and it works.
If you haven't read through the Ember Data Guide in the last week or two (it's changed a lot), I would spend a few minutes on it.
The fix for this error (as of ember-data 1.0.0.beta.6) for me was to make sure that the JSON returned from the server included an "id" field for each model, BUT not to explicitly declare the id when setting up the Ember DS.Model.
jbuilder template:
json.scans do
json.array! #scans do |scan|
json.id scan.id # This prop has to be there
json.name scan.name
end
end
Ember model:
EmberApp.Scan = DS.Model.extend(
// Don't include the id prop here
name: DS.attr("string")
)
I want the onBlur event of the input box to trigger the CheckMask() validation function to see whether the data entered by the user is correct or not. The data format is abc 123. If the input isn't in the correct format, I want to display an error message.
Can someone help me modify this code? I'm not getting the correct result.
function CheckMask() {
var value = $('.Mask-tttnnn').val();
if (value.length <= 3) {
char = value.substring(value.length - 1);
if (!(isNaN(char))) {
var newval = value.substring(0, value.length - 1);
$(Mask - tttnnn).val(newval);
}
}
if (value.length > 3) {
char = value.substring(value.length - 1);
if (isNaN(char)) {
var newval = value.substring(0, value.length - 1);
$(Mask - tttnnn).val(newval);
}
}
}
HTML:
<input id="checkval" value="" type="text" class="Mask-tttnnn" onBlur="CheckMask()" />
Step 1: remove the onBlur from your HTML. Keep code and mark-up separate.
Step 2: construct a regular expression you would like to validate. See http://www.regular-expressions.info/javascript.html
[A-Z]{3}[0-9]{3}
Step 3: attach a function to the blur event of your input using jQuery
$('checkval').blur(function () {
// check $(this).val() against the regex
// alert if it fails or whatever you want to do
});