dimanche 10 décembre 2017

Validate From time To Time in ember using ember-cp-validations

I have two fields, "From time" and "To time". I want to validate From time should be lesser than To time and To time should be grater than From time.

Means validation should be depend on both the fields. Is there any way to validate such a scenario ?

'fieldData.FROM_TIME': function(keyToGetData){
    return validator(function(value, options, model) {
        let fromTime = value;
        let toTime = model.get(keyToGetData);
        if(fromTime){
            let fromHours = fromTime.hours;
            let fromMins = fromTime.minutes;

            // make validation only if toTime is there
            if(toTime){
                let toHours = toTime.hours;
                let toMins = toTime.minutes;
                if(fromHours > toHours || ( fromHours===toHours && fromMins > toMins) ){
                    return 'From time must be earlier than To time.';
                }
            }
            return true;
        }
        return 'This field can not be blank';
    });
},

'fieldData.TO_TIME': function(keyToGetData){
    return validator(function(value, options, model) {
        let fromTime = model.get(keyToGetData);
        let toTime = value;

        if(toTime){
            let toHours = toTime.hours;
            let toMins = toTime.minutes;

            // make validation only if fromTime is there
            if(fromTime){
                let fromHours = fromTime.hours;
                let fromMins = fromTime.minutes;

                if(fromHours > toHours || (fromHours===toHours && fromMins >= toMins) ){
                    return 'To time must be later than From time.';
                }
            }
            return true;
        }
        return 'This field can not be blank';
    });
}

With the above code I can validate fields with happy path.

But, if we set From time as 11:20am & To time as 11:20am so error will show on To time field. Now if we change From time as 11:19am so still it shows me error on To time. I want solution on such a scenario.

I am using ember-cp-validations.

Thanks.




Aucun commentaire:

Enregistrer un commentaire